{"base_sha": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/cogwheel0/conduit/pull/615", "id": "046967849dc294597e7a1c90904013a3eaffc8ec6d02760615cb7fa2f1ae1be9", "preparation_mode": "source-only", "snapshot": {"base_ref": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "base_sha": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "body": "", "head_ref": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "head_sha": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "name": "conduit", "number": 615, "owner": "cogwheel0", "pr_url": "https://github.com/cogwheel0/conduit/pull/615", "title": ""}}, "head_sha": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "metadata": {"group_id": "0ec24d3d43b712a4082c02707f42307b7d3c7728c2fd1063dd3389c91d43914c", "snapshot": {"base_sha": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "external_requirements": [{"commit": "01f4282f1ffe0d6212f58d3afbeae21fffd0c4be", "path": "openwebui-src", "snapshot": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "type": "submodule"}, {"commit": "212f328fb6fbcdb88367da3eee47e82afa757a46", "path": "third_party/katex", "snapshot": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "type": "submodule"}, {"commit": "ddb951169592bf089518ba19dbf3bf7ffa8d3c35", "path": "third_party/mermaid", "snapshot": "4b66a1c4e1a8d66fc0365605c32b04335093fd77", "type": "submodule"}, {"commit": "01f4282f1ffe0d6212f58d3afbeae21fffd0c4be", "path": "openwebui-src", "snapshot": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "type": "submodule"}, {"commit": "212f328fb6fbcdb88367da3eee47e82afa757a46", "path": "third_party/katex", "snapshot": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "type": "submodule"}, {"commit": "ddb951169592bf089518ba19dbf3bf7ffa8d3c35", "path": "third_party/mermaid", "snapshot": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "type": "submodule"}], "head_sha": "c944e5e2aca392629cabd9ed3e715a18c8d0b444", "objects": 1445, "objects_sha256": "8f807331d2be34d9060f6dfb707b3153a861df28c7553ee014647d3ea1656675", "patch_sha256": "400bace640fc8289a7a95f3fffd99aa431e94e0ebc3524b93f2cd85910124989"}}, "pr_number": 615, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "e1399199d2da", "description": "Credential capture was fenced by a navigation generation and trusted origin rather than a committed, live document. Redirects, same-origin URL changes, or delayed asynchronous reads could let stale page results drive cookie or JWT capture.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A2", "action_type": "improvement", "category": "refactor", "commit_sha": "d518b1f51978", "description": "Repeated ownership and live-document checks across credential-capture paths were easy to apply inconsistently; the code did not centralize the distinction between a live document, a moved-away WebView, and lost ownership.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "86ed9d371a0d", "description": "When a platform omitted onPageCommitVisible, onLoadStop had no committed ticket, so automatic and manual proxy-auth completion could stall with the page still loading.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "5055be46a4ee", "description": "A delayed document-commit callback for an old URL could replace the active navigation and incorrectly grant the old document ownership.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A5", "action_type": "fix", "category": "security", "commit_sha": "b9e89f8a39e0", "description": "History callbacks were adopted without correlating them to the live WebView or distinguishing a loading redirect from a non-loading History API change. This could treat a provisional redirect as committed or let a stale callback mutate a newer navigation.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "b9e89f8a39e0", "description": "When load-stop adopted a redirect and advanced the document generation, an in-flight capture remained in the queue and could block capture on the final document.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "b9e89f8a39e0", "description": "A failed WebView URL or loading-state read during load-stop could leave proxy sign-in loading indefinitely without a verification error; a stale failure could also overwrite newer navigation state.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "fcabdc4eecf1", "description": "A verified same-document history change reset capture but did not clear loading or inspect the replacement ticket, so automatic capture could be missed when no new load-stop arrived.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "fcabdc4eecf1", "description": "A password-field inspection result could publish a persistent JWT-wait requirement after the WebView URL had moved away from the captured document, potentially making later automatic capture wait indefinitely.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A10", "action_type": "fix", "category": "bug", "commit_sha": "43b0fc4f927f", "description": "Overlapping asynchronous history callbacks could be processed out of order, allowing an older URL update to interfere with the latest navigation; pending history work also needed to be dropped on invalidation.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A11", "action_type": "fix", "category": "bug", "commit_sha": "86f215490b5e", "description": "An exception during a fire-and-forget history update could escape as an unhandled asynchronous error and interrupt processing of later queued URLs.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}, {"action_id": "A12", "action_type": "fix", "category": "bug", "commit_sha": "d0381e9f4017", "description": "The document fence discarded URL fragments, treating hash-only history changes as no-ops. Hash-routed login transitions could therefore miss automatic cookie and JWT re-inspection.", "file_path": "lib/features/auth/views/proxy_auth_page.dart"}], "commits_under_review": [{"author": "cogwheel0", "date": "2026-08-04T19:28:13Z", "files": [{"additions": 40, "deletions": 3, "filename": "lib/features/auth/views/proxy_auth_page.dart", "patch": "@@ -366,6 +366,27 @@ final class ProxyAuthDocumentFence {\n bool ownsDocument(int generation, String url) =>\n ownsGeneration(generation) && _documentKey == _key(url);\n \n+ /// Commits the URL reported when the current main-frame navigation finishes.\n+ ///\n+ /// The callback URL must still match the WebView's current URL so a delayed\n+ /// completion from an older navigation cannot take ownership of a newer one.\n+ bool commitDocument({\n+ required int generation,\n+ required String callbackUrl,\n+ required String currentUrl,\n+ }) {\n+ final callbackKey = _key(callbackUrl);\n+ if (!ownsGeneration(generation) || callbackKey != _key(currentUrl)) {\n+ return false;\n+ }\n+\n+ // WKWebView does not emit another load-start callback for HTTP redirects.\n+ // Adopt the final URL only after the finish callback and the live WebView\n+ // agree, keeping delayed completions from older navigations fenced out.\n+ _documentKey = callbackKey;\n+ return true;\n+ }\n+\n static String _key(String url) {\n final uri = Uri.tryParse(url);\n if (uri == null) return url;\n@@ -513,10 +534,26 @@ class _ProxyAuthPageState extends ConsumerState {\n });\n }\n \n- Future _onPageFinished(String url) async {\n+ Future _onPageFinished(\n+ InAppWebViewController controller,\n+ String url,\n+ ) async {\n if (!mounted) return;\n final generation = _documentFence.generation;\n- if (!_ownsCaptureDocument(generation, url)) return;\n+ final currentUrl = await controller.getUrl();\n+ if (!mounted ||\n+ currentUrl == null ||\n+ !_documentFence.commitDocument(\n+ generation: generation,\n+ callbackUrl: url,\n+ currentUrl: currentUrl.toString(),\n+ )) {\n+ DebugLogger.log(\n+ 'Ignoring stale proxy auth page completion',\n+ scope: 'auth/proxy',\n+ );\n+ return;\n+ }\n DebugLogger.auth(\n 'Proxy auth page finished: ${webViewOriginForLog(url)}',\n scope: 'auth/proxy',\n@@ -1226,7 +1263,7 @@ class _ProxyAuthPageState extends ConsumerState {\n if (urlText == null || urlText.isEmpty) {\n return;\n }\n- await _onPageFinished(urlText);\n+ await _onPageFinished(controller, urlText);\n },\n onReceivedError: (controller, request, error) {\n _onWebResourceError(request, error);", "status": "modified"}, {"additions": 38, "deletions": 0, "filename": "test/features/auth/views/proxy_auth_page_test.dart", "patch": "@@ -39,6 +39,44 @@ void main() {\n fence.ownsDocument(fence.generation, 'https://chat.example/auth'),\n ).isFalse();\n });\n+\n+ test('commits the final URL of an HTTP redirect without another start', () {\n+ final fence = ProxyAuthDocumentFence();\n+ fence.startNavigation('https://chat.example/');\n+ final generation = fence.generation;\n+\n+ final committed = fence.commitDocument(\n+ generation: generation,\n+ callbackUrl: 'https://auth.example/?rd=https%3A%2F%2Fchat.example%2F',\n+ currentUrl: 'https://auth.example/?rd=https%3A%2F%2Fchat.example%2F',\n+ );\n+\n+ check(committed).isTrue();\n+ check(\n+ fence.ownsDocument(\n+ generation,\n+ 'https://auth.example/?rd=https%3A%2F%2Fchat.example%2F',\n+ ),\n+ ).isTrue();\n+ });\n+\n+ test('rejects a delayed completion after a newer navigation starts', () {\n+ final fence = ProxyAuthDocumentFence();\n+ fence.startNavigation('https://auth.example/login');\n+ fence.startNavigation('https://chat.example/auth');\n+ final currentGeneration = fence.generation;\n+\n+ final committed = fence.commitDocument(\n+ generation: currentGeneration,\n+ callbackUrl: 'https://auth.example/login',\n+ currentUrl: 'https://chat.example/auth',\n+ );\n+\n+ check(committed).isFalse();\n+ check(\n+ fence.ownsDocument(currentGeneration, 'https://chat.example/auth'),\n+ ).isTrue();\n+ });\n });\n \n group('refreshProxyAuthWebView', () {", "status": "modified"}], "message": "fix(auth): finish proxy login after iOS redirects", "sha": "c944e5e2aca392629cabd9ed3e715a18c8d0b444"}], "post_review_commits": ["e1399199d2da517a6057df7635a0a06471a1f84e", "d518b1f5197811ea503af66abe5caf3ad115bbdf", "86ed9d371a0d4b2158f306adf570d5f98d7a1746", "5055be46a4eec54e4a8575f27d1adc5fda739ee1", "b9e89f8a39e065521316650ff6c3b20bf9dbbc73", "fcabdc4eecf15bd1c72617cf33ddeda0bfbd050b", "43b0fc4f927f4192d88924babf9837298e499f48", "86f215490b5efdd01ed6b7ad846f5189b0f8705f", "d0381e9f401751f5f297afe2b765f1ac6d979068"], "pr_author": "cogwheel0", "pr_title": "fix(auth): finish proxy login after iOS redirects", "repo_name": "cogwheel0/conduit"}, "repo": "cogwheel0/conduit", "snapshot": "snapshots/0ec24d3d43b712a4082c02707f42307b7d3c7728c2fd1063dd3389c91d43914c.pack", "split": "eval", "task_id": "046967849dc294597e7a1c90904013a3eaffc8ec6d02760615cb7fa2f1ae1be9"} {"base_sha": "112ea06816408eccf50f94ea0115642d1fdd6550", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/rheged-studio/agent-skills/pull/98", "id": "0565e5666eda03e32adaae13825277da0d591f28cfd144b2f870f405a754d3e8", "preparation_mode": "source-only", "snapshot": {"base_ref": "112ea06816408eccf50f94ea0115642d1fdd6550", "base_sha": "112ea06816408eccf50f94ea0115642d1fdd6550", "body": "", "head_ref": "ec39566f05bdc6d9a47f486e5f8381b18d2bbe3a", "head_sha": "ec39566f05bdc6d9a47f486e5f8381b18d2bbe3a", "name": "agent-skills", "number": 98, "owner": "rheged-studio", "pr_url": "https://github.com/rheged-studio/agent-skills/pull/98", "title": ""}}, "head_sha": "ec39566f05bdc6d9a47f486e5f8381b18d2bbe3a", "metadata": {"group_id": "122aad9b56de4c8d8ae84ddd94b6b1da0cc13bf7436ef7eeeb03ce3e3c8c4acb", "snapshot": {"base_sha": "112ea06816408eccf50f94ea0115642d1fdd6550", "external_requirements": [], "head_sha": "ec39566f05bdc6d9a47f486e5f8381b18d2bbe3a", "objects": 320, "objects_sha256": "3aeef761b83e2adb5925bbc1d4e9782ce69d2acf4aa3b4fa209ee0d64a889b90", "patch_sha256": "28f8bc4bf3f4a32b99dada4908d9e7281485f713b6ae411b3b2ede4530f6af79"}}, "pr_number": 98, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "46bb55a032e7", "description": "The README did not specify that an unrecognised `linearWritebackDefault` value falls back to a `no` prompt default.", "file_path": "skills/cleanup-repo/README.md"}, {"action_id": "A2", "action_type": "fix", "category": "documentation", "commit_sha": "46bb55a032e7", "description": "The skill instructions specified the fallback for an absent `linearWritebackDefault` key but left the behavior for unrecognised values unclear, potentially leading to an incorrect Step 10 prompt default.", "file_path": "skills/cleanup-repo/SKILL.md"}], "commits_under_review": [{"author": "RobEasthope", "date": "2026-07-04T20:20:13Z", "files": [{"additions": 2, "deletions": 1, "filename": "infrastructure/dogfood-config/cleanup-repo.json", "patch": "@@ -2,5 +2,6 @@\n \"linearTeamName\": \"ACME Skunkworks\",\n \"issueKeys\": [\"A\"],\n \"mainBranch\": \"main\",\n- \"protectedBranches\": [\"main\"]\n+ \"protectedBranches\": [\"main\"],\n+ \"linearWritebackDefault\": \"no\"\n }", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "skills/cleanup-repo/README.md", "patch": "@@ -31,6 +31,7 @@ issue-IDs won't match.\n | `issueKeys` | Team-key prefixes that may appear in branch names; the issue-ID regex is built from these. | `[\"A\"]` |\n | `mainBranch` | Trunk a branch must be merged into to count as merged; both passes diff against `origin/`. Set it for repos whose trunk isn't `main` (`master`, `develop`, …). | `\"main\"` |\n | `protectedBranches` | Branches never deleted, locally or remotely. | `[\"main\"]` |\n+| `linearWritebackDefault` | Seeds the yes/no default of the Step 10 Linear `Done` writeback prompt (`\"yes\"` / `\"no\"`); the interactive gate always stays, so it never auto-applies. Absent → `\"no\"`. | `\"no\"` |\n \n > **Base branch.** The trunk defaults to `origin/main`; set the `mainBranch`\n > config key for repositories on `master` / `develop` / similar — both merge", "status": "modified"}, {"additions": 11, "deletions": 5, "filename": "skills/cleanup-repo/SKILL.md", "patch": "@@ -15,7 +15,7 @@ compatibility: >-\n Linear MCP server; if it is unavailable, skip that step silently. The\n filesystem pass needs Node.js ≥22.\n metadata:\n- version: 0.3.3\n+ version: 0.4.0\n author: Rob Easthope\n allowed-tools: Read, Bash(git:*), Bash(gh:*), Bash(node:*), mcp__linear-server__get_issue, mcp__linear-server__save_issue, mcp__linear-server__list_issue_statuses\n ---\n@@ -33,7 +33,7 @@ rationale and the deliberately-deferred future extensions.\n \n ## Configuration\n \n-Four knobs live in [`config.json`](config.json) beside this file. Read it at the\n+Five knobs live in [`config.json`](config.json) beside this file. Read it at the\n start of a run and use its values throughout. Edit your copied `config.json` to\n match the consuming repo:\n \n@@ -43,6 +43,7 @@ match the consuming repo:\n | `issueKeys` | Team-key prefixes that may appear in branch names. The issue-ID regex is built from these. | `[\"A\"]` |\n | `mainBranch` | The trunk a branch must be merged into to count as merged — both passes diff against `origin/`. Set it for repos whose trunk is `master`, `develop`, or similar. | `\"main\"` |\n | `protectedBranches` | Branches that are **never** deleted, locally or remotely. | `[\"main\"]` |\n+| `linearWritebackDefault` | Seeds the yes/no default of the Step 10 Linear `Done` writeback prompt — `\"yes\"` pre-fills yes, `\"no\"` pre-fills no. The interactive gate always stays; this never auto-applies. Absent → treated as `\"no\"`. | `\"no\"` |\n \n Build the issue-ID regex **deterministically**: escape each key's regex\n metacharacters, and when there is more than one key wrap the alternation in\n@@ -338,9 +339,14 @@ runs **after** worktree removal so a just-emptied worktree parent (e.g.\n If any Linear issues from Step 4 are not `Done`:\n \n - Ask: `These Linear issues are linked to merged branches but aren't Done. Set\n- them to Done? (yes/no)`. **Default no** — Linear's GitHub integration normally\n- handles this on PR merge, so this exists only for the rare case where it didn't\n- fire (e.g. the issue ID was added after the merge).\n+ them to Done? (yes/no)`. Seed the default from `linearWritebackDefault` —\n+ `\"yes\"` pre-fills the prompt with yes, `\"no\"` pre-fills no; treat an absent key\n+ as `\"no\"`. The prompt is always shown and the answer always confirmed — the\n+ knob only moves the default, it never auto-applies. The default is `no` because\n+ Linear's GitHub integration normally handles this on PR merge, so the writeback\n+ exists only for the rare case where it didn't fire (e.g. the issue ID was added\n+ after the merge); a repo not wired to that integration can flip the default to\n+ `yes`.\n - If yes:\n - Resolve the live `Done` state ID **once** via\n `mcp__linear-server__list_issue_statuses` with `team: ` —", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "skills/cleanup-repo/config.example.json", "patch": "@@ -2,5 +2,6 @@\n \"linearTeamName\": \"Your Linear Team\",\n \"issueKeys\": [\"ABC\", \"XYZ\"],\n \"mainBranch\": \"main\",\n- \"protectedBranches\": [\"main\"]\n+ \"protectedBranches\": [\"main\"],\n+ \"linearWritebackDefault\": \"no\"\n }", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "skills/cleanup-repo/package.json", "patch": "@@ -1,6 +1,6 @@\n {\n \"name\": \"@acme-skunkworks/skill-cleanup-repo\",\n- \"version\": \"0.3.3\",\n+ \"version\": \"0.4.0\",\n \"private\": true,\n \"description\": \"Agent skill: clean up merged Git branches and worktrees, plus a filesystem-hygiene pass (empty directories and orphan node_modules).\",\n \"keywords\": [", "status": "modified"}], "message": "feat(cleanup-repo): make the Linear Done writeback default configurable\n\nAdd a linearWritebackDefault config knob (no | yes) that seeds the\nStep 10 Linear Done-writeback prompt default. The interactive gate always\nstays — the knob only moves the default, it never auto-applies. An absent\nkey is treated as no, preserving the existing backward-compatible\nbehaviour.\n\nThe key is added to the tracked dogfood-config source and config.example.json\n(key-set parity holds; validate:skills green), documented in the SKILL.md and\nREADME Configuration tables, and the bundle version is bumped 0.3.3 -> 0.4.0\nin lockstep (package.json + SKILL.md metadata.version).", "sha": "133a18710f4f3ab088510d7d41a4eb4ba454a73c"}, {"author": "RobEasthope", "date": "2026-07-04T20:21:18Z", "files": [{"additions": 41, "deletions": 0, "filename": "changelog/20260704-202046-a-701-cleanup-repo-configurable-linear-writeback-default.md", "patch": "@@ -0,0 +1,41 @@\n+---\n+title: \"cleanup-repo: make the Linear Done writeback default configurable\"\n+release_note: \"cleanup-repo gains a linearWritebackDefault config knob that seeds the Step 10 Linear Done-writeback prompt default (\\\"yes\\\" or \\\"no\\\"). Repos not wired to Linear's GitHub integration can now flip the default to yes without editing the SKILL.md. The interactive gate always stays — the knob only moves the default, it never auto-applies — and an absent key is treated as no, preserving the existing behaviour.\"\n+created_at: \"2026-07-04T20:20:46Z\"\n+merged_at:\n+branch: \"a-701-cleanup-repo-make-the-linear-done-writeback-default\"\n+pr:\n+commit:\n+merge_strategy:\n+author: \"hello@robeasthope.com\"\n+co_authors: []\n+category: feature\n+breaking: false\n+issues: [\"A-701\"]\n+stats:\n+ files_changed:\n+ loc_added:\n+ loc_removed:\n+ commits:\n+---\n+\n+## Added\n+\n+**cleanup-repo:** the optional Linear `Done` writeback (Step 10) previously prompted\n+*\"Set them to Done? (yes/no)\"* with a **hardcoded default of no**. That default is\n+right for repos wired to Linear's GitHub integration — which moves an issue to Done\n+on PR merge, leaving the writeback for the rare case it didn't fire — but a repo not\n+using that integration had no way to flip the default short of editing the\n+`SKILL.md`.\n+\n+A new `linearWritebackDefault` config knob (`\"no\"` | `\"yes\"`) now seeds the Step 10\n+prompt default. `\"yes\"` pre-fills the prompt with yes, `\"no\"` pre-fills no, and an\n+absent key is treated as `\"no\"` — so existing consumers are unaffected. The\n+interactive confirmation always stays; the knob only moves the default and never\n+silently mass-transitions issues.\n+\n+The key is added to both the tracked dogfood-config source and\n+`config.example.json` (their key sets stay identical, as `pnpm validate:skills`\n+enforces), documented in the SKILL.md and README Configuration tables, and the\n+`cleanup-repo` bundle version is bumped `0.3.3` → `0.4.0`\n+([A-701](https://linear.app/acme-skunkworks/issue/A-701)).", "status": "added"}], "message": "docs(changelog): add A-701 cleanup-repo writeback-default entry", "sha": "ec39566f05bdc6d9a47f486e5f8381b18d2bbe3a"}], "post_review_commits": ["46bb55a032e72f361f945006cfcc375e1491deac", "fd615e1ac1dd2c60b4ef79a4cfeb70b6f455b45e"], "pr_author": "RobEasthope", "pr_title": "feat(cleanup-repo): make the Linear Done writeback default configurable", "repo_name": "rheged-studio/agent-skills"}, "repo": "rheged-studio/agent-skills", "snapshot": "snapshots/122aad9b56de4c8d8ae84ddd94b6b1da0cc13bf7436ef7eeeb03ce3e3c8c4acb.pack", "split": "eval", "task_id": "0565e5666eda03e32adaae13825277da0d591f28cfd144b2f870f405a754d3e8"} {"base_sha": "5ca2f5e08db5b310875373e26ee236e8a761c1a0", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/Joker5514/conqueror-studios-web/pull/21", "id": "0a5958d43f2497f4bb157639dd43828bac5e697d3363963cbba2a1ff71216563", "preparation_mode": "source-only", "snapshot": {"base_ref": "5ca2f5e08db5b310875373e26ee236e8a761c1a0", "base_sha": "5ca2f5e08db5b310875373e26ee236e8a761c1a0", "body": "", "head_ref": "4eb91523e52a1681c0a0763cd2d07f163aa938e4", "head_sha": "4eb91523e52a1681c0a0763cd2d07f163aa938e4", "name": "conqueror-studios-web", "number": 21, "owner": "Joker5514", "pr_url": "https://github.com/Joker5514/conqueror-studios-web/pull/21", "title": ""}}, "head_sha": "4eb91523e52a1681c0a0763cd2d07f163aa938e4", "metadata": {"group_id": "0606db1a32303e2f7d0446d364922fdbbbf026428b720414ec2549ba5e7f019a", "snapshot": {"base_sha": "5ca2f5e08db5b310875373e26ee236e8a761c1a0", "external_requirements": [], "head_sha": "4eb91523e52a1681c0a0763cd2d07f163aa938e4", "objects": 168, "objects_sha256": "2ca19d9a8ba35877970536c0e6099c31343825be9e9582d3942c9f5d9c4b4bb1", "patch_sha256": "1d1b298f3d5e61a8d78eb0b73481b0bfb3779cf5cd8c9efb63dd3367065a3a63"}}, "pr_number": 21, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "documentation", "commit_sha": "0130fa54cf93", "description": "The gateway identifiers and default routing mode were still documented as provisional, leaving the Phase-1 configuration contract unclear.", "file_path": "docs/ai-gateway.md"}, {"action_id": "A2", "action_type": "improvement", "category": "documentation", "commit_sha": "0130fa54cf93", "description": "The gateway documentation did not explain which secrets remain server-only or distinguish the browser-based BYOK demo from production server-side callers.", "file_path": "docs/ai-gateway.md"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "29c749b95445", "description": "The curl example used $GATEWAY_SECRET without exporting it into the shell; a value in .env.local alone would not populate the curl header.", "file_path": "docs/ai-gateway.md"}, {"action_id": "A4", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "Installed versions of Next.js, PostCSS, Axios, brace-expansion, and Sharp had high-severity audit findings, including SSRF, proxy, denial-of-service, path-traversal, and libvips vulnerabilities.", "file_path": "package.json"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "Provider alias lookup could accept inherited Object.prototype properties such as toString as though they were configured provider aliases.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A6", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "Upstream mode forwarded the entire client JSON body, including arbitrary undocumented fields, despite the request contract saying extra fields were ignored.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A7", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "An upstream URL could use unencrypted HTTP for a nonlocal host, exposing the forwarded shared-secret header and request content in transit; malformed URLs were not rejected as configuration errors.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "An upstream fetch had no application-level deadline, so a stalled upstream could hold gateway capacity indefinitely.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "If an upstream returned a successful HTTP status with invalid JSON, the gateway returned an error body with that successful status.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A10", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "Rate limiting ran after shared-secret authorization, leaving failed authentication attempts outside the per-IP limit.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A11", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "A valid JSON body of null or an array was not rejected before property access; null could cause a server error instead of a 400 validation response.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A12", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "The gateway did not cap total message content, allowing oversized prompts to consume excessive memory or provider tokens.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A13", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "Optional model, temperature, and max_tokens fields were only range-checked when already numeric, so malformed values such as model: 7 or temperature: \"high\" bypassed validation.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A14", "action_type": "improvement", "category": "other", "commit_sha": "29c749b95445", "description": "Unexpected gateway failures were logged without their error message or stack, making server-side diagnosis difficult.", "file_path": "src/app/api/gateway/route.ts"}, {"action_id": "A15", "action_type": "improvement", "category": "other", "commit_sha": "29c749b95445", "description": "Authorization behavior for an unset secret, missing or incorrect headers, and a matching header lacked direct tests.", "file_path": "src/lib/ai-gateway/auth.test.js"}, {"action_id": "A16", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "A missing provider key produced a client-visible error containing the internal environment-variable name.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A17", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "OpenAI-compatible requests always sent max_tokens, which newer reasoning and GPT-5 models reject in favor of max_completion_tokens.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A18", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "Outbound OpenAI/xAI and Anthropic fetches had no deadline, so stalled providers could leave gateway requests waiting indefinitely without a controlled timeout response.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A19", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "Malformed OpenAI-compatible responses with no valid choice or non-string message content could be reported as successful empty output.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A20", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "OpenAI-compatible safety refusals supplied in the refusal field were returned as blank output instead of being surfaced to callers.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A21", "action_type": "fix", "category": "bug", "commit_sha": "29c749b95445", "description": "An Anthropic response without a content array could be reported as a successful empty response rather than an invalid provider response.", "file_path": "src/lib/ai-gateway/providers.ts"}, {"action_id": "A22", "action_type": "fix", "category": "security", "commit_sha": "29c749b95445", "description": "Successful gateway responses exposed complete, unsanitized provider payloads through raw, potentially leaking provider metadata or sensitive fields to clients.", "file_path": "src/lib/ai-gateway/providers.ts"}], "commits_under_review": [{"author": "Joker5514", "date": "2026-07-21T08:25:34Z", "files": [{"additions": 18, "deletions": 0, "filename": ".env.example", "patch": "@@ -36,3 +36,21 @@ NEXUS_URL=http://localhost:8000\n # Production: https://ai-bridge-production.up.railway.app\n # Local dev: http://localhost:8001\n BRIDGE_URL=http://localhost:8001\n+\n+# ─── AI Gateway (POST /api/gateway) — all server-only ─────────────────────────\n+# Names below marked PROPOSED in docs/ai-gateway.md until confirmed.\n+\n+# Shared secret for inbound X-Gateway-Secret header (PROPOSED)\n+GATEWAY_SECRET=\n+\n+# Routing: \"direct\" (default) calls providers from this app; \"upstream\" forwards\n+# AI_GATEWAY_MODE=direct\n+# AI_GATEWAY_UPSTREAM_URL=https://example.com/api/gateway\n+\n+# Provider keys (required in direct mode for the providers you use)\n+OPENAI_API_KEY=\n+ANTHROPIC_API_KEY=\n+XAI_API_KEY=\n+\n+# Optional: public path only — never put secrets in NEXT_PUBLIC_*\n+# NEXT_PUBLIC_GATEWAY_URL=/api/gateway", "status": "modified"}, {"additions": 222, "deletions": 0, "filename": "docs/ai-gateway.md", "patch": "@@ -0,0 +1,222 @@\n+# AI Gateway (Phase 1)\n+\n+Server-side multi-provider AI entrypoint for **conqueror-studios-web**. \n+Browser code must never hold provider API keys.\n+\n+## Endpoint paths\n+\n+| Path | Status |\n+|------|--------|\n+| **`POST /api/gateway`** | **Stable entrypoint (this PR)** |\n+| `POST /api/ai` | **Does not exist** — do not use |\n+| `POST /api/nexus` | Separate OrchestrAI Nexus `/run` proxy (session auth, not this gateway) |\n+| `GET /api/nexus/schema` | Separate AI Bridge tools schema proxy |\n+\n+Implementation: `src/app/api/gateway/route.ts`\n+\n+---\n+\n+## Authentication\n+\n+| Item | Value | Notes |\n+|------|--------|--------|\n+| Header name | **`X-Gateway-Secret`** | **PROPOSED** — confirm before locking the contract |\n+| Env var (server-only) | **`GATEWAY_SECRET`** | **PROPOSED** — must match header value |\n+| Comparison | Constant-time (SHA-256 digests) | Missing/wrong → `401` |\n+| Unset secret | `503` `gateway_misconfigured` | Fail closed |\n+\n+**Never** put `GATEWAY_SECRET` or provider keys in `NEXT_PUBLIC_*`.\n+\n+---\n+\n+## Request\n+\n+```http\n+POST /api/gateway\n+Content-Type: application/json\n+X-Gateway-Secret: \n+```\n+\n+```json\n+{\n+ \"provider\": \"openai\",\n+ \"model\": \"gpt-4o-mini\",\n+ \"messages\": [\n+ { \"role\": \"user\", \"content\": \"Say hello in one sentence.\" }\n+ ],\n+ \"temperature\": 0.4,\n+ \"max_tokens\": 256\n+}\n+```\n+\n+Or single-turn:\n+\n+```json\n+{\n+ \"provider\": \"anthropic\",\n+ \"input\": \"Summarize AI safety in one sentence.\"\n+}\n+```\n+\n+### Providers (canonical)\n+\n+| `provider` | Aliases | Server env (PROPOSED) |\n+|------------|---------|------------------------|\n+| `openai` | — | `OPENAI_API_KEY` |\n+| `anthropic` | `claude` | `ANTHROPIC_API_KEY` |\n+| `xai` | `grok` | `XAI_API_KEY` |\n+\n+### Success response\n+\n+```json\n+{\n+ \"id\": \"chatcmpl-…\",\n+ \"provider\": \"openai\",\n+ \"model\": \"gpt-4o-mini\",\n+ \"output_text\": \"Hello…\",\n+ \"usage\": {\n+ \"input_tokens\": 12,\n+ \"output_tokens\": 8,\n+ \"total_tokens\": 20\n+ },\n+ \"raw\": {}\n+}\n+```\n+\n+### Error response\n+\n+```json\n+{\n+ \"error\": \"Unauthorized\",\n+ \"code\": \"unauthorized\"\n+}\n+```\n+\n+Common codes: `unauthorized`, `gateway_misconfigured`, `rate_limited`, `invalid_provider`, `invalid_messages`, `provider_misconfigured`, `provider_error`, `provider_unreachable`.\n+\n+---\n+\n+## Routing modes\n+\n+| `AI_GATEWAY_MODE` | Behavior |\n+|-------------------|----------|\n+| *(unset)* / `direct` | **Default.** Call OpenAI / Anthropic / xAI HTTP APIs from this route using server env keys. |\n+| `upstream` | Forward JSON body to `AI_GATEWAY_UPSTREAM_URL` (server-only absolute URL). Forwards `X-Gateway-Secret` if present. |\n+\n+**PROPOSED** env names: `AI_GATEWAY_MODE`, `AI_GATEWAY_UPSTREAM_URL`.\n+\n+Related existing env (not used by `/api/gateway` unless you point upstream at them yourself):\n+\n+- `NEXUS_URL` — used only by `POST /api/nexus` → Nexus `/run`\n+- `BRIDGE_URL` — used only by `GET /api/nexus/schema` → Bridge tools schema\n+\n+---\n+\n+## Required / optional env vars (names only)\n+\n+### Server-only (runtime — set in Vercel Project → Settings → Environment Variables)\n+\n+| Name | Required when | Public? |\n+|------|----------------|---------|\n+| `GATEWAY_SECRET` | Always (for `/api/gateway`) | **No** |\n+| `OPENAI_API_KEY` | `direct` + provider `openai` | **No** |\n+| `ANTHROPIC_API_KEY` | `direct` + provider `anthropic` | **No** |\n+| `XAI_API_KEY` | `direct` + provider `xai` | **No** |\n+| `AI_GATEWAY_MODE` | Optional (`direct` \\| `upstream`) | **No** |\n+| `AI_GATEWAY_UPSTREAM_URL` | `upstream` mode | **No** |\n+\n+### Public (browser-safe) — **not used by the gateway**\n+\n+| Name | Purpose |\n+|------|---------|\n+| `NEXT_PUBLIC_SUPABASE_URL` | Supabase client |\n+| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Supabase anon |\n+\n+Optional public helper for **client apps that only need the path** (never the secret):\n+\n+| Name | Purpose |\n+|------|---------|\n+| `NEXT_PUBLIC_GATEWAY_URL` | Optional; e.g. `/api/gateway` — path only, no secrets |\n+\n+---\n+\n+## Vercel configuration notes\n+\n+1. Add secrets under **Runtime** environments (Production + Preview). \n+ Build-time injection is unnecessary for these keys; the route uses `process.env` at request time.\n+2. **Do not** prefix provider keys or `GATEWAY_SECRET` with `NEXT_PUBLIC_`.\n+3. After changing env vars, redeploy Preview/Production so serverless instances pick them up.\n+4. Preview deploys from PRs should use **Preview** env values (can use separate test keys + a distinct `GATEWAY_SECRET`).\n+5. Rotate secrets by: create new value → update Vercel → redeploy → update callers → revoke old value.\n+\n+---\n+\n+## Rate limiting\n+\n+In-process sliding window via `src/lib/rateLimit.ts`: **30 requests / IP / minute** for `/api/gateway`. \n+Multi-instance Vercel traffic is not globally coordinated; upgrade to Redis later if needed.\n+\n+---\n+\n+## Local test\n+\n+```bash\n+# From repo root — ensure .env.local has GATEWAY_SECRET + at least one provider key\n+bun run dev\n+```\n+\n+```bash\n+curl -sS -X POST \"http://localhost:3000/api/gateway\" \\\n+ -H \"Content-Type: application/json\" \\\n+ -H \"X-Gateway-Secret: $GATEWAY_SECRET\" \\\n+ -d \"{\\\"provider\\\":\\\"openai\\\",\\\"input\\\":\\\"Reply with the word pong only.\\\"}\"\n+```\n+\n+Expect `200` and JSON with `output_text`. \n+Without the header (or with wrong secret): `401`. \n+Without `GATEWAY_SECRET` in env: `503`.\n+\n+---\n+\n+## Vercel Preview test\n+\n+1. Open the PR Preview URL (Vercel deployment).\n+2. Ensure Preview env has `GATEWAY_SECRET` and provider keys.\n+3. Run the same curl against `https:///api/gateway`.\n+4. Confirm Network tab in the browser never receives provider keys (only your app’s server may call the gateway with the secret — and the secret must not be embedded in client bundles).\n+\n+---\n+\n+## Minimal server-side call (example)\n+\n+```ts\n+// Server Component / Route Handler / Server Action only — not in client components\n+const res = await fetch(`${process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : \"http://localhost:3000\"}/api/gateway`, {\n+ method: \"POST\",\n+ headers: {\n+ \"Content-Type\": \"application/json\",\n+ \"X-Gateway-Secret\": process.env.GATEWAY_SECRET!, // server-only\n+ },\n+ body: JSON.stringify({\n+ provider: \"xai\",\n+ model: \"grok-2\",\n+ messages: [{ role: \"user\", content: \"Hi\" }],\n+ }),\n+});\n+```\n+\n+For **other repos** calling this deployment, store `GATEWAY_SECRET` and the production base URL as server-only env on the caller; never ship them as `VITE_*` / `NEXT_PUBLIC_*`.\n+\n+---\n+\n+## Identifier summary (PROPOSED)\n+\n+| Role | Identifier |\n+|------|------------|\n+| Auth header | `X-Gateway-Secret` |\n+| Auth env | `GATEWAY_SECRET` |\n+| Mode env | `AI_GATEWAY_MODE` |\n+| Upstream URL env | `AI_GATEWAY_UPSTREAM_URL` |\n+| Provider keys | `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `XAI_API_KEY` |\n+\n+If any of these conflict with an org-wide standard, rename before merge and update this doc + `src/lib/ai-gateway/constants.ts` together.", "status": "added"}, {"additions": 204, "deletions": 0, "filename": "src/app/api/gateway/route.ts", "patch": "@@ -0,0 +1,204 @@\n+import { type NextRequest, NextResponse } from \"next/server\";\n+import { authorizeGatewayRequest } from \"@/lib/ai-gateway/auth\";\n+import {\n+ AI_GATEWAY_MODE_ENV,\n+ AI_GATEWAY_UPSTREAM_URL_ENV,\n+ GATEWAY_AUTH_HEADER_NAME,\n+ PROVIDER_ALIASES,\n+ type SupportedProvider,\n+ SUPPORTED_PROVIDERS,\n+} from \"@/lib/ai-gateway/constants\";\n+import { callProviderDirect, ProviderHttpError } from \"@/lib/ai-gateway/providers\";\n+import type {\n+ GatewayErrorResponse,\n+ GatewayMessage,\n+ GatewayRequestBody,\n+ GatewaySuccessResponse,\n+} from \"@/lib/ai-gateway/types\";\n+import { rateLimit } from \"@/lib/rateLimit\";\n+\n+/**\n+ * POST /api/gateway\n+ *\n+ * Server-side AI gateway. Provider keys never leave this process.\n+ * Auth: shared secret header (see docs/ai-gateway.md).\n+ *\n+ * Body: { provider, model?, messages? | input?, temperature?, max_tokens? }\n+ * Response: { id, provider, model, output_text, usage?, raw? }\n+ */\n+\n+export const runtime = \"nodejs\";\n+export const dynamic = \"force-dynamic\";\n+\n+function jsonError(\n+ status: number,\n+ error: string,\n+ code?: string,\n+): NextResponse {\n+ return NextResponse.json(code ? { error, code } : { error }, { status });\n+}\n+\n+function clientIp(req: NextRequest): string {\n+ const xff = req.headers.get(\"x-forwarded-for\");\n+ const parts = xff?.split(\",\").map((p) => p.trim()).filter(Boolean) ?? [];\n+ // Prefer rightmost hop (same rationale as waitlist server action).\n+ return parts.at(-1) ?? req.headers.get(\"x-real-ip\")?.trim() ?? \"unknown\";\n+}\n+\n+function normalizeMessages(body: GatewayRequestBody): GatewayMessage[] | null {\n+ if (Array.isArray(body.messages) && body.messages.length > 0) {\n+ const out: GatewayMessage[] = [];\n+ for (const m of body.messages) {\n+ if (!m || typeof m !== \"object\") return null;\n+ const role = m.role;\n+ const content = m.content;\n+ if (\n+ (role !== \"system\" && role !== \"user\" && role !== \"assistant\") ||\n+ typeof content !== \"string\"\n+ ) {\n+ return null;\n+ }\n+ out.push({ role, content });\n+ }\n+ return out;\n+ }\n+ if (typeof body.input === \"string\" && body.input.trim()) {\n+ return [{ role: \"user\", content: body.input.trim() }];\n+ }\n+ return null;\n+}\n+\n+function resolveProvider(raw: string | undefined): SupportedProvider | null {\n+ if (!raw || typeof raw !== \"string\") return null;\n+ const key = raw.trim().toLowerCase();\n+ return PROVIDER_ALIASES[key] ?? null;\n+}\n+\n+function gatewayMode(): \"direct\" | \"upstream\" {\n+ const mode = process.env[AI_GATEWAY_MODE_ENV]?.trim().toLowerCase();\n+ return mode === \"upstream\" ? \"upstream\" : \"direct\";\n+}\n+\n+async function forwardUpstream(\n+ body: GatewayRequestBody,\n+ inboundSecretHeader: string | null,\n+): Promise {\n+ const upstream = process.env[AI_GATEWAY_UPSTREAM_URL_ENV]?.trim();\n+ if (!upstream) {\n+ return jsonError(\n+ 503,\n+ \"AI gateway upstream is not configured\",\n+ \"upstream_misconfigured\",\n+ );\n+ }\n+\n+ const headers: Record = {\n+ \"Content-Type\": \"application/json\",\n+ };\n+ // Forward the same shared secret if the upstream uses the same contract.\n+ if (inboundSecretHeader) {\n+ headers[GATEWAY_AUTH_HEADER_NAME] = inboundSecretHeader;\n+ }\n+\n+ let res: Response;\n+ try {\n+ res = await fetch(upstream, {\n+ method: \"POST\",\n+ headers,\n+ body: JSON.stringify(body),\n+ });\n+ } catch {\n+ return jsonError(502, \"Upstream gateway unreachable\", \"upstream_unreachable\");\n+ }\n+\n+ const data: unknown = await res.json().catch(() => ({\n+ error: \"Invalid upstream response\",\n+ code: \"upstream_invalid_response\",\n+ }));\n+ return NextResponse.json(data, { status: res.status });\n+}\n+\n+export async function POST(\n+ req: NextRequest,\n+): Promise> {\n+ // ── Auth (shared secret header) ───────────────────────────────────────────\n+ const auth = authorizeGatewayRequest(req);\n+ if (!auth.ok) {\n+ return jsonError(auth.status, auth.error, auth.code);\n+ }\n+\n+ // ── Rate limit (per IP) ───────────────────────────────────────────────────\n+ const ip = clientIp(req);\n+ const limit = rateLimit(`ai-gateway:${ip}`, { windowMs: 60_000, max: 30 });\n+ if (!limit.ok) {\n+ return jsonError(429, \"Too many requests\", \"rate_limited\");\n+ }\n+\n+ // ── Parse body ────────────────────────────────────────────────────────────\n+ let body: GatewayRequestBody;\n+ try {\n+ body = (await req.json()) as GatewayRequestBody;\n+ } catch {\n+ return jsonError(400, \"Invalid JSON body\", \"invalid_json\");\n+ }\n+\n+ const provider = resolveProvider(body.provider);\n+ if (!provider) {\n+ return jsonError(\n+ 400,\n+ `provider is required and must be one of: ${SUPPORTED_PROVIDERS.join(\", \")}`,\n+ \"invalid_provider\",\n+ );\n+ }\n+\n+ const messages = normalizeMessages(body);\n+ if (!messages) {\n+ return jsonError(\n+ 400,\n+ \"Provide non-empty messages[] or input string\",\n+ \"invalid_messages\",\n+ );\n+ }\n+\n+ if (typeof body.temperature === \"number\") {\n+ if (!Number.isFinite(body.temperature) || body.temperature < 0 || body.temperature > 2) {\n+ return jsonError(400, \"temperature must be between 0 and 2\", \"invalid_temperature\");\n+ }\n+ }\n+ if (typeof body.max_tokens === \"number\") {\n+ if (!Number.isFinite(body.max_tokens) || body.max_tokens < 1 || body.max_tokens > 128_000) {\n+ return jsonError(400, \"max_tokens is out of range\", \"invalid_max_tokens\");\n+ }\n+ }\n+\n+ // ── Route: upstream proxy or direct providers ─────────────────────────────\n+ if (gatewayMode() === \"upstream\") {\n+ const secretHeader =\n+ req.headers.get(GATEWAY_AUTH_HEADER_NAME) ??\n+ req.headers.get(\"x-gateway-secret\");\n+ return forwardUpstream({ ...body, provider }, secretHeader) as Promise<\n+ NextResponse\n+ >;\n+ }\n+\n+ try {\n+ const result = await callProviderDirect({\n+ provider,\n+ model: body.model,\n+ messages,\n+ temperature: body.temperature,\n+ maxTokens: body.max_tokens,\n+ });\n+ return NextResponse.json(result, {\n+ status: 200,\n+ headers: { \"Cache-Control\": \"no-store\" },\n+ });\n+ } catch (err) {\n+ if (err instanceof ProviderHttpError) {\n+ return jsonError(err.status, err.message, err.code);\n+ }\n+ // Do not log full error objects that might contain request material with secrets.\n+ console.error(\"[api/gateway] unexpected failure\");\n+ return jsonError(500, \"Internal server error\", \"internal_error\");\n+ }\n+}", "status": "added"}, {"additions": 16, "deletions": 0, "filename": "src/lib/ai-gateway/auth.test.js", "patch": "@@ -0,0 +1,16 @@\n+import { describe, expect, test } from \"bun:test\";\n+import { secretsEqual } from \"./auth.ts\";\n+\n+describe(\"secretsEqual\", () => {\n+ test(\"matches identical secrets\", () => {\n+ expect(secretsEqual(\"gateway-secret-value\", \"gateway-secret-value\")).toBe(true);\n+ });\n+\n+ test(\"rejects different secrets of same length\", () => {\n+ expect(secretsEqual(\"aaaaaaaa\", \"bbbbbbbb\")).toBe(false);\n+ });\n+\n+ test(\"rejects different lengths without throwing\", () => {\n+ expect(secretsEqual(\"short\", \"much-longer-secret\")).toBe(false);\n+ });\n+});", "status": "added"}, {"additions": 53, "deletions": 0, "filename": "src/lib/ai-gateway/auth.ts", "patch": "@@ -0,0 +1,53 @@\n+import { createHash, timingSafeEqual } from \"node:crypto\";\n+import type { NextRequest } from \"next/server\";\n+import {\n+ GATEWAY_AUTH_HEADER_NAME,\n+ GATEWAY_SECRET_ENV,\n+} from \"./constants\";\n+\n+/**\n+ * Constant-time string compare via SHA-256 digests so unequal lengths\n+ * do not short-circuit on Buffer length.\n+ */\n+export function secretsEqual(a: string, b: string): boolean {\n+ const ha = createHash(\"sha256\").update(a, \"utf8\").digest();\n+ const hb = createHash(\"sha256\").update(b, \"utf8\").digest();\n+ return timingSafeEqual(ha, hb);\n+}\n+\n+export type GatewayAuthResult =\n+ | { ok: true }\n+ | { ok: false; status: 401 | 503; error: string; code: string };\n+\n+/**\n+ * Require GATEWAY_SECRET env and matching X-Gateway-Secret header.\n+ * Does not log secret values.\n+ */\n+export function authorizeGatewayRequest(req: NextRequest): GatewayAuthResult {\n+ const configured = process.env[GATEWAY_SECRET_ENV]?.trim();\n+ if (!configured) {\n+ return {\n+ ok: false,\n+ status: 503,\n+ error: \"AI gateway is not configured\",\n+ code: \"gateway_misconfigured\",\n+ };\n+ }\n+\n+ // Node/undici lower-cases header names; also accept exact constant for clarity.\n+ const provided =\n+ req.headers.get(GATEWAY_AUTH_HEADER_NAME) ??\n+ req.headers.get(GATEWAY_AUTH_HEADER_NAME.toLowerCase()) ??\n+ req.headers.get(\"x-gateway-secret\");\n+\n+ if (!provided || !secretsEqual(provided, configured)) {\n+ return {\n+ ok: false,\n+ status: 401,\n+ error: \"Unauthorized\",\n+ code: \"unauthorized\",\n+ };\n+ }\n+\n+ return { ok: true };\n+}", "status": "added"}, {"additions": 59, "deletions": 0, "filename": "src/lib/ai-gateway/constants.ts", "patch": "@@ -0,0 +1,59 @@\n+/**\n+ * AI Gateway identifier constants.\n+ *\n+ * All names below that are not already used elsewhere in this repo are\n+ * marked PROPOSED — confirm before treating them as permanent contracts.\n+ */\n+\n+/** PROPOSED: inbound auth header name (case-insensitive on read). */\n+export const GATEWAY_AUTH_HEADER_NAME = \"X-Gateway-Secret\";\n+\n+/**\n+ * PROPOSED: server-only env var that holds the shared secret.\n+ * Must match the value clients send in GATEWAY_AUTH_HEADER_NAME.\n+ * Never use NEXT_PUBLIC_* for this.\n+ */\n+export const GATEWAY_SECRET_ENV = \"GATEWAY_SECRET\";\n+\n+/**\n+ * PROPOSED: routing mode.\n+ * - \"direct\" (default): call provider HTTP APIs from this Next.js route\n+ * - \"upstream\": forward the request body to AI_GATEWAY_UPSTREAM_URL\n+ */\n+export const AI_GATEWAY_MODE_ENV = \"AI_GATEWAY_MODE\";\n+\n+/**\n+ * PROPOSED: absolute URL of an upstream gateway (used when mode is \"upstream\").\n+ * Example: https://nexus-production.up.railway.app/api/gateway\n+ * Server-only. Distinct from NEXUS_URL (/run orchestration) and BRIDGE_URL (tools).\n+ */\n+export const AI_GATEWAY_UPSTREAM_URL_ENV = \"AI_GATEWAY_UPSTREAM_URL\";\n+\n+/** PROPOSED: OpenAI secret (server-only). */\n+export const OPENAI_API_KEY_ENV = \"OPENAI_API_KEY\";\n+\n+/** PROPOSED: Anthropic secret (server-only). */\n+export const ANTHROPIC_API_KEY_ENV = \"ANTHROPIC_API_KEY\";\n+\n+/** PROPOSED: xAI / Grok secret (server-only). */\n+export const XAI_API_KEY_ENV = \"XAI_API_KEY\";\n+\n+/** Canonical provider ids accepted by POST /api/gateway. */\n+export const SUPPORTED_PROVIDERS = [\"openai\", \"anthropic\", \"xai\"] as const;\n+\n+export type SupportedProvider = (typeof SUPPORTED_PROVIDERS)[number];\n+\n+/** Aliases mapped to canonical provider ids (browser / legacy names). */\n+export const PROVIDER_ALIASES: Record = {\n+ openai: \"openai\",\n+ anthropic: \"anthropic\",\n+ claude: \"anthropic\",\n+ xai: \"xai\",\n+ grok: \"xai\",\n+};\n+\n+export const DEFAULT_MODELS: Record = {\n+ openai: \"gpt-4o-mini\",\n+ anthropic: \"claude-sonnet-4-5-20250929\",\n+ xai: \"grok-2\",\n+};", "status": "added"}, {"additions": 243, "deletions": 0, "filename": "src/lib/ai-gateway/providers.ts", "patch": "@@ -0,0 +1,243 @@\n+import {\n+ ANTHROPIC_API_KEY_ENV,\n+ DEFAULT_MODELS,\n+ OPENAI_API_KEY_ENV,\n+ type SupportedProvider,\n+ XAI_API_KEY_ENV,\n+} from \"./constants\";\n+import type {\n+ GatewayMessage,\n+ GatewaySuccessResponse,\n+ GatewayUsage,\n+} from \"./types\";\n+\n+export class ProviderHttpError extends Error {\n+ readonly status: number;\n+ readonly code: string;\n+\n+ constructor(message: string, status: number, code: string) {\n+ super(message);\n+ this.name = \"ProviderHttpError\";\n+ this.status = status;\n+ this.code = code;\n+ }\n+}\n+\n+function requireKey(envName: string): string {\n+ const key = process.env[envName]?.trim();\n+ if (!key) {\n+ throw new ProviderHttpError(\n+ `Provider not configured (${envName} missing)`,\n+ 503,\n+ \"provider_misconfigured\",\n+ );\n+ }\n+ return key;\n+}\n+\n+function asRecord(value: unknown): Record | null {\n+ if (value && typeof value === \"object\" && !Array.isArray(value)) {\n+ return value as Record;\n+ }\n+ return null;\n+}\n+\n+function openaiCompatibleUsage(raw: Record | null): GatewayUsage | undefined {\n+ const usage = asRecord(raw?.usage);\n+ if (!usage) return undefined;\n+ const prompt = typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : undefined;\n+ const completion =\n+ typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : undefined;\n+ const total = typeof usage.total_tokens === \"number\" ? usage.total_tokens : undefined;\n+ return {\n+ input_tokens: prompt,\n+ output_tokens: completion,\n+ total_tokens: total ?? (prompt !== undefined && completion !== undefined ? prompt + completion : undefined),\n+ };\n+}\n+\n+async function callOpenAiCompatible(options: {\n+ provider: SupportedProvider;\n+ endpoint: string;\n+ apiKey: string;\n+ model: string;\n+ messages: GatewayMessage[];\n+ temperature?: number;\n+ maxTokens?: number;\n+}): Promise {\n+ const { provider, endpoint, apiKey, model, messages, temperature, maxTokens } = options;\n+\n+ const body: Record = {\n+ model,\n+ messages,\n+ };\n+ if (typeof temperature === \"number\") body.temperature = temperature;\n+ if (typeof maxTokens === \"number\") body.max_tokens = maxTokens;\n+\n+ let res: Response;\n+ try {\n+ res = await fetch(endpoint, {\n+ method: \"POST\",\n+ headers: {\n+ \"Content-Type\": \"application/json\",\n+ Authorization: `Bearer ${apiKey}`,\n+ },\n+ body: JSON.stringify(body),\n+ });\n+ } catch {\n+ throw new ProviderHttpError(\"Provider unreachable\", 502, \"provider_unreachable\");\n+ }\n+\n+ const raw: unknown = await res.json().catch(() => ({}));\n+ const record = asRecord(raw);\n+\n+ if (!res.ok) {\n+ // Never surface provider bodies that might echo secrets; keep message generic.\n+ throw new ProviderHttpError(\n+ `Provider error (${provider})`,\n+ res.status >= 400 && res.status < 600 ? res.status : 502,\n+ \"provider_error\",\n+ );\n+ }\n+\n+ const choices = Array.isArray(record?.choices) ? record.choices : [];\n+ const first = asRecord(choices[0]);\n+ const message = asRecord(first?.message);\n+ const content = message?.content;\n+ const output_text = typeof content === \"string\" ? content : \"\";\n+\n+ return {\n+ id: typeof record?.id === \"string\" ? record.id : crypto.randomUUID(),\n+ provider,\n+ model,\n+ output_text,\n+ usage: openaiCompatibleUsage(record),\n+ raw,\n+ };\n+}\n+\n+async function callAnthropic(options: {\n+ model: string;\n+ messages: GatewayMessage[];\n+ temperature?: number;\n+ maxTokens?: number;\n+}): Promise {\n+ const apiKey = requireKey(ANTHROPIC_API_KEY_ENV);\n+ const { model, messages, temperature, maxTokens } = options;\n+\n+ const systemParts = messages\n+ .filter((m) => m.role === \"system\")\n+ .map((m) => m.content)\n+ .filter(Boolean);\n+ const chatMessages = messages\n+ .filter((m) => m.role === \"user\" || m.role === \"assistant\")\n+ .map((m) => ({ role: m.role, content: m.content }));\n+\n+ if (chatMessages.length === 0) {\n+ throw new ProviderHttpError(\"messages must include at least one user turn\", 400, \"invalid_request\");\n+ }\n+\n+ const body: Record = {\n+ model,\n+ max_tokens: typeof maxTokens === \"number\" ? maxTokens : 1024,\n+ messages: chatMessages,\n+ };\n+ if (systemParts.length > 0) body.system = systemParts.join(\"\\n\\n\");\n+ if (typeof temperature === \"number\") body.temperature = temperature;\n+\n+ let res: Response;\n+ try {\n+ res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n+ method: \"POST\",\n+ headers: {\n+ \"Content-Type\": \"application/json\",\n+ \"x-api-key\": apiKey,\n+ \"anthropic-version\": \"2023-06-01\",\n+ },\n+ body: JSON.stringify(body),\n+ });\n+ } catch {\n+ throw new ProviderHttpError(\"Provider unreachable\", 502, \"provider_unreachable\");\n+ }\n+\n+ const raw: unknown = await res.json().catch(() => ({}));\n+ const record = asRecord(raw);\n+\n+ if (!res.ok) {\n+ throw new ProviderHttpError(\n+ \"Provider error (anthropic)\",\n+ res.status >= 400 && res.status < 600 ? res.status : 502,\n+ \"provider_error\",\n+ );\n+ }\n+\n+ const contentBlocks = Array.isArray(record?.content) ? record.content : [];\n+ const texts: string[] = [];\n+ for (const block of contentBlocks) {\n+ const b = asRecord(block);\n+ if (b?.type === \"text\" && typeof b.text === \"string\") texts.push(b.text);\n+ }\n+\n+ const usageRaw = asRecord(record?.usage);\n+ const usage: GatewayUsage | undefined = usageRaw\n+ ? {\n+ input_tokens:\n+ typeof usageRaw.input_tokens === \"number\" ? usageRaw.input_tokens : undefined,\n+ output_tokens:\n+ typeof usageRaw.output_tokens === \"number\" ? usageRaw.output_tokens : undefined,\n+ total_tokens:\n+ typeof usageRaw.input_tokens === \"number\" && typeof usageRaw.output_tokens === \"number\"\n+ ? usageRaw.input_tokens + usageRaw.output_tokens\n+ : undefined,\n+ }\n+ : undefined;\n+\n+ return {\n+ id: typeof record?.id === \"string\" ? record.id : crypto.randomUUID(),\n+ provider: \"anthropic\",\n+ model: typeof record?.model === \"string\" ? record.model : model,\n+ output_text: texts.join(\"\"),\n+ usage,\n+ raw,\n+ };\n+}\n+\n+export async function callProviderDirect(options: {\n+ provider: SupportedProvider;\n+ model?: string;\n+ messages: GatewayMessage[];\n+ temperature?: number;\n+ maxTokens?: number;\n+}): Promise {\n+ const model = options.model?.trim() || DEFAULT_MODELS[options.provider];\n+ const { messages, temperature, maxTokens } = options;\n+\n+ switch (options.provider) {\n+ case \"openai\":\n+ return callOpenAiCompatible({\n+ provider: \"openai\",\n+ endpoint: \"https://api.openai.com/v1/chat/completions\",\n+ apiKey: requireKey(OPENAI_API_KEY_ENV),\n+ model,\n+ messages,\n+ temperature,\n+ maxTokens,\n+ });\n+ case \"xai\":\n+ return callOpenAiCompatible({\n+ provider: \"xai\",\n+ endpoint: \"https://api.x.ai/v1/chat/completions\",\n+ apiKey: requireKey(XAI_API_KEY_ENV),\n+ model,\n+ messages,\n+ temperature,\n+ maxTokens,\n+ });\n+ case \"anthropic\":\n+ return callAnthropic({ model, messages, temperature, maxTokens });\n+ default: {\n+ const _exhaustive: never = options.provider;\n+ throw new ProviderHttpError(`Unsupported provider: ${String(_exhaustive)}`, 400, \"unsupported_provider\");\n+ }\n+ }\n+}", "status": "added"}, {"additions": 42, "deletions": 0, "filename": "src/lib/ai-gateway/types.ts", "patch": "@@ -0,0 +1,42 @@\n+import type { SupportedProvider } from \"./constants\";\n+\n+export interface GatewayMessage {\n+ role: \"system\" | \"user\" | \"assistant\";\n+ content: string;\n+}\n+\n+/**\n+ * Minimal POST body for /api/gateway.\n+ * Extra fields are ignored (not forwarded to providers unless documented).\n+ */\n+export interface GatewayRequestBody {\n+ provider: string;\n+ model?: string;\n+ /** Chat-style messages (preferred). */\n+ messages?: GatewayMessage[];\n+ /** Convenience single-turn prompt when messages is omitted. */\n+ input?: string;\n+ temperature?: number;\n+ max_tokens?: number;\n+}\n+\n+export interface GatewayUsage {\n+ input_tokens?: number;\n+ output_tokens?: number;\n+ total_tokens?: number;\n+}\n+\n+export interface GatewaySuccessResponse {\n+ id: string;\n+ provider: SupportedProvider;\n+ model: string;\n+ output_text: string;\n+ usage?: GatewayUsage;\n+ /** Provider payload; omit secrets. Present for debugging on success only. */\n+ raw?: unknown;\n+}\n+\n+export interface GatewayErrorResponse {\n+ error: string;\n+ code?: string;\n+}", "status": "added"}], "message": "feat(ai-gateway): add server-side POST /api/gateway with shared-secret auth", "sha": "4eb91523e52a1681c0a0763cd2d07f163aa938e4"}], "post_review_commits": ["0130fa54cf93947e73b237deb8b3cad2dc3ff517", "29c749b9544578cb09a3a6e59f23dd3e8f548327"], "pr_author": "Joker5514", "pr_title": "feat(ai-gateway): server-side POST /api/gateway (shared secret, multi-provider)", "repo_name": "Joker5514/conqueror-studios-web"}, "repo": "Joker5514/conqueror-studios-web", "snapshot": "snapshots/0606db1a32303e2f7d0446d364922fdbbbf026428b720414ec2549ba5e7f019a.pack", "split": "eval", "task_id": "0a5958d43f2497f4bb157639dd43828bac5e697d3363963cbba2a1ff71216563"} {"base_sha": "4d9d7ee857c6559783b4016d77dee41501f83f1b", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/tonythethompson/Olive-Studio/pull/280", "id": "0dd705328c773f1211d05430081479d3787ae1510bf39a07464adef5f9f3a0a3", "preparation_mode": "source-only", "snapshot": {"base_ref": "4d9d7ee857c6559783b4016d77dee41501f83f1b", "base_sha": "4d9d7ee857c6559783b4016d77dee41501f83f1b", "body": "", "head_ref": "fed9cf285033c5d73cac8385af33c44dfd65abdb", "head_sha": "fed9cf285033c5d73cac8385af33c44dfd65abdb", "name": "Olive-Studio", "number": 280, "owner": "tonythethompson", "pr_url": "https://github.com/tonythethompson/Olive-Studio/pull/280", "title": ""}}, "head_sha": "fed9cf285033c5d73cac8385af33c44dfd65abdb", "metadata": {"group_id": "1255846e73e3b2f34a007c2457af9c89fc21fe8b8736db6170e94649e550a255", "snapshot": {"base_sha": "4d9d7ee857c6559783b4016d77dee41501f83f1b", "external_requirements": [], "head_sha": "fed9cf285033c5d73cac8385af33c44dfd65abdb", "objects": 860, "objects_sha256": "13c82e6222212260168a8bc487eb7b3e9dba7997c7862d14f3d531b6c39c3414", "patch_sha256": "36a20f166057aed5513fd2c8d1a526e51310ae5086de21a32031e3815c7e438e"}}, "pr_number": 280, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "69998cc8c312", "description": "The publish workflow ran Python 3.10, which lacks tomllib, but did not install its tomli fallback; reading pyproject.toml would fail.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "69998cc8c312", "description": "Both verification steps passed indented multiline source to python -c, causing an IndentationError and blocking publication.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "69998cc8c312", "description": "The MCP dependency gate matched any requirement containing the digit 2, so it could approve incompatible mcp>=2 and reject valid below-2 constraints; it also identified dependencies by a loose name prefix.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "69998cc8c312", "description": "The package reported runtime version 0.1.0 despite being distributed as 0.5.0, giving clients and generated knowledge-base metadata the wrong version.", "file_path": "olive-mcp-server/olive_mcp_server/__init__.py"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "20b73ec70726", "description": "The MCP pin check sampled only a fixed set of 2.x versions, missing constraints that allowed other 2.x releases, such as mcp>2.99.99,<3.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "2807c3bc2e28", "description": "The candidate-based pin check passed wildcard operands such as 1.* to Version(), raising InvalidVersion and blocking valid releases.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "2807c3bc2e28", "description": "Candidate probing could treat narrow 2.x ranges as safe when none of its sampled versions matched, despite the dependency lacking a below-2 ceiling.", "file_path": ".github/workflows/publish-mcp-pypi.yml"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "14709d9fbc5f", "description": "The pin gate treated exact or compatible pins to any major other than 2 as safe, allowing incompatible MCP 3.x dependencies to be published.", "file_path": "olive-mcp-server/scripts/check_mcp_pin.py"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "860214e9feca", "description": "The new pin checker sampled only a static version grid, so arbitrary incompatible pins such as mcp==2.5.5 or narrow 2.x ranges could escape detection.", "file_path": "olive-mcp-server/scripts/check_mcp_pin.py"}, {"action_id": "A10", "action_type": "cleanup", "category": "style", "commit_sha": "c9a8526ab310", "description": "The candidate parser caught every exception and silently continued, potentially hiding errors unrelated to invalid version strings; it also used a try-except-continue pattern flagged by static analysis.", "file_path": "olive-mcp-server/scripts/check_mcp_pin.py"}, {"action_id": "A11", "action_type": "fix", "category": "security", "commit_sha": "12f49eb9d040", "description": "The dependency override and lockfile still permitted nanoid 3.3.17, below the patched 3.3.18 release for GHSA-2v37-7h3g-55p8.", "file_path": "pnpm-workspace.yaml"}], "commits_under_review": [{"author": "tonythethompson", "date": "2026-08-13T13:48:24Z", "files": [{"additions": 73, "deletions": 0, "filename": ".github/workflows/publish-mcp-pypi.yml", "patch": "@@ -0,0 +1,73 @@\n+name: Publish Olive MCP Server to PyPI\n+\n+on:\n+ push:\n+ tags:\n+ - \"mcp-server/v*\"\n+\n+jobs:\n+ publish:\n+ runs-on: ubuntu-latest\n+ permissions:\n+ id-token: write\n+ contents: read\n+ steps:\n+ - uses: actions/checkout@v4\n+\n+ - uses: actions/setup-python@v5\n+ with:\n+ python-version: \"3.10\"\n+\n+ - name: Install build tools\n+ run: pip install build\n+\n+ - name: Verify version matches tag\n+ working-directory: olive-mcp-server\n+ run: |\n+ TAG_VERSION=\"${GITHUB_REF_NAME#mcp-server/v}\"\n+ PKG_VERSION=$(python -c \"\n+ try:\n+ import tomllib\n+ except ModuleNotFoundError:\n+ import tomli as tomllib\n+ with open('pyproject.toml', 'rb') as f:\n+ data = tomllib.load(f)\n+ print(data['project']['version'])\n+ \")\n+ echo \"Tag version: $TAG_VERSION\"\n+ echo \"Package version: $PKG_VERSION\"\n+ if [ \"$TAG_VERSION\" != \"$PKG_VERSION\" ]; then\n+ echo \"::error::Version mismatch: tag says $TAG_VERSION but pyproject.toml says $PKG_VERSION\"\n+ exit 1\n+ fi\n+\n+ - name: Verify mcp dependency is pinned below 2\n+ working-directory: olive-mcp-server\n+ run: |\n+ MCP_CONSTRAINT=$(python -c \"\n+ try:\n+ import tomllib\n+ except ModuleNotFoundError:\n+ import tomli as tomllib\n+ with open('pyproject.toml', 'rb') as f:\n+ data = tomllib.load(f)\n+ deps = data.get('project', {}).get('dependencies', [])\n+ for dep in deps:\n+ if dep.lower().startswith('mcp'):\n+ print(dep)\n+ break\n+ \")\n+ echo \"MCP constraint: $MCP_CONSTRAINT\"\n+ if ! echo \"$MCP_CONSTRAINT\" | grep -qE 'mcp[<>=!~ ]+.*2'; then\n+ echo \"::error::mcp dependency must be pinned below 2 (e.g. 'mcp<2')\"\n+ exit 1\n+ fi\n+\n+ - name: Build package\n+ working-directory: olive-mcp-server\n+ run: python -m build\n+\n+ - name: Publish to PyPI\n+ uses: pypa/gh-action-pypi-publish@release/v1\n+ with:\n+ packages-dir: olive-mcp-server/dist/", "status": "added"}, {"additions": 22, "deletions": 2, "filename": "olive-mcp-server/pyproject.toml", "patch": "@@ -4,9 +4,23 @@ build-backend = \"setuptools.build_meta\"\n \n [project]\n name = \"olive-mcp-server\"\n-version = \"0.1.0\"\n-description = \"MCP server for Microsoft Olive model optimization guidance\"\n+version = \"0.5.0\"\n+description = \"MCP server for Microsoft Olive model optimization\"\n+license = {text = \"MIT\"}\n requires-python = \">=3.10\"\n+keywords = [\"olive\", \"onnx\", \"model-optimization\", \"mcp\", \"fastmcp\"]\n+classifiers = [\n+ \"Development Status :: 4 - Beta\",\n+ \"Programming Language :: Python :: 3\",\n+ \"Programming Language :: Python :: 3.10\",\n+ \"Programming Language :: Python :: 3.11\",\n+ \"Programming Language :: Python :: 3.12\",\n+ \"Programming Language :: Python :: 3.13\",\n+ \"License :: OSI Approved :: MIT License\",\n+ \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n+ \"Intended Audience :: Developers\",\n+ \"Operating System :: OS Independent\",\n+]\n dependencies = [\n \"mcp>=1.0.0,<2\",\n \"requests>=2.32.0\",\n@@ -15,6 +29,11 @@ dependencies = [\n \"numpy>=1.24.0,<3\",\n ]\n \n+[project.urls]\n+Homepage = \"https://github.com/asiraky/olive-studio\"\n+Repository = \"https://github.com/asiraky/olive-studio\"\n+\"Bug Tracker\" = \"https://github.com/asiraky/olive-studio/issues\"\n+\n [project.optional-dependencies]\n dev = [\n \"pytest>=8.0.0\",\n@@ -28,6 +47,7 @@ semantic = [\n ]\n \n [project.scripts]\n+olive-mcp = \"olive_mcp_server.mcp_server:main\"\n olive-mcp-server = \"olive_mcp_server.mcp_server:main\"\n \n [tool.setuptools.packages.find]", "status": "modified"}], "message": "ci: add MCP PyPI publish workflow with mcp<2 pin verification\n\nAdd GitHub Actions workflow that publishes the Olive MCP server to\nPyPI on mcp-server/v* tags. Includes a verification step that checks\nthe mcp dependency remains pinned below 2 to prevent breaking changes\nfrom the upstream mcp 2.x release.\n\nGenerated with [Devin](https://devin.ai)\n\nCo-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>", "sha": "fed9cf285033c5d73cac8385af33c44dfd65abdb"}], "post_review_commits": ["69998cc8c31227e10879f28bb91924247a6aeb80", "20b73ec707262247c6001488b01ba16ded9bd10b", "2807c3bc2e28d566649c61ff14b9654e03d7b353", "12f49eb9d040db106feec0340a04c2798b93afc1", "14709d9fbc5faa593f583df69f217766ae29e190", "860214e9feca1ffe2d668758bf5743ffd88a7ea8", "c9a8526ab31077a6aba845df2947eaadc7b33172", "33958aaf9ac60420b3b4e6912dd3a68ef11939a6"], "pr_author": "tonythethompson", "pr_title": "ci: add MCP PyPI publish workflow with mcp<2 pin verification", "repo_name": "tonythethompson/Olive-Studio"}, "repo": "tonythethompson/Olive-Studio", "snapshot": "snapshots/1255846e73e3b2f34a007c2457af9c89fc21fe8b8736db6170e94649e550a255.pack", "split": "eval", "task_id": "0dd705328c773f1211d05430081479d3787ae1510bf39a07464adef5f9f3a0a3"} {"base_sha": "f842653366a3c46cc9f805f34fde0bc30f5ec138", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/NextCommerceCo/docs/pull/32", "id": "0f048a85ac719cd17cb8faa63e592dcc8f41471b0b0ac9f6ae7ef128db90ed2b", "preparation_mode": "source-only", "snapshot": {"base_ref": "f842653366a3c46cc9f805f34fde0bc30f5ec138", "base_sha": "f842653366a3c46cc9f805f34fde0bc30f5ec138", "body": "", "head_ref": "ac14050718109b3128d2cd508175a0c33245e54d", "head_sha": "ac14050718109b3128d2cd508175a0c33245e54d", "name": "docs", "number": 32, "owner": "NextCommerceCo", "pr_url": "https://github.com/NextCommerceCo/docs/pull/32", "title": ""}}, "head_sha": "ac14050718109b3128d2cd508175a0c33245e54d", "metadata": {"group_id": "033613e7c812ebcba4841a8327cbbbe651df90a8700e0be7bab841b261f96f32", "snapshot": {"base_sha": "f842653366a3c46cc9f805f34fde0bc30f5ec138", "external_requirements": [], "head_sha": "ac14050718109b3128d2cd508175a0c33245e54d", "objects": 489, "objects_sha256": "5eade68fa58f41cd4157c167f76682f8166b6b484ce0862f95b762e7c104e164", "patch_sha256": "a10edb928b473fcf093ae7d40fa01a6bb45ae9d78d209f7f006e16f8bdc1b8e0"}}, "pr_number": 32, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "26173bcdcdd7", "description": "The 404 page presented “Search the docs” as a second link to /docs, even though search opens through the ⌘K palette and has no URL. This duplicated the docs-index link and misled users about where the link would take them.", "file_path": "app/not-found.tsx"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "26173bcdcdd7", "description": "Sitemap changelog entries used build time as lastModified instead of their required publishedAt date, reporting an inaccurate modification date for each entry.", "file_path": "app/sitemap.ts"}, {"action_id": "A3", "action_type": "improvement", "category": "other", "commit_sha": "26173bcdcdd7", "description": "The search-index size limit was hard-coded to 6 MB, so builds could not configure the budget through SEARCH_INDEX_BUDGET_BYTES.", "file_path": "scripts/check-search-budget.mjs"}, {"action_id": "A4", "action_type": "improvement", "category": "other", "commit_sha": "26173bcdcdd7", "description": "When the built search index was missing, the error only suggested running the build; it gave no useful guidance if the build had already run but the static search route wrote the index to a different path.", "file_path": "scripts/check-search-budget.mjs"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "81300ecdea8d", "description": "The initial environment-variable override silently fell back to the default for invalid values such as `abc` or `0`, and accepted other non-positive-integer values. A mistyped budget could therefore go unnoticed instead of failing the check.", "file_path": "scripts/check-search-budget.mjs"}], "commits_under_review": [{"author": "next-devin", "date": "2026-09-03T04:05:04Z", "files": [{"additions": 2, "deletions": 0, "filename": ".github/workflows/ci.yml", "patch": "@@ -21,6 +21,8 @@ jobs:\n \n - run: npm run build\n \n+ - run: npm run check-search-budget\n+\n security-audit:\n runs-on: ubuntu-latest\n steps:", "status": "modified"}, {"additions": 33, "deletions": 0, "filename": "app/not-found.tsx", "patch": "@@ -0,0 +1,33 @@\n+import Link from 'next/link';\n+\n+const recoveryLinks = [\n+ { label: 'Browse all docs', href: '/docs' },\n+ { label: 'Search the docs (press ⌘K)', href: '/docs' },\n+ { label: 'Changelog', href: '/changelog' },\n+ { label: 'Developer docs', href: 'https://developers.nextcommerce.com' },\n+ { label: 'Agent index (llms.txt)', href: '/llms.txt' },\n+];\n+\n+export default function NotFound() {\n+ return (\n+
\n+
\n+

Page not found

\n+

\n+ The page you asked for does not exist or has moved; try one of these instead.\n+

\n+ \n+
\n+
\n+ );\n+}", "status": "added"}, {"additions": 11, "deletions": 0, "filename": "app/robots.ts", "patch": "@@ -0,0 +1,11 @@\n+import { siteConfig } from '@/lib/config';\n+import type { MetadataRoute } from 'next';\n+\n+export const dynamic = 'force-static';\n+\n+export default function robots(): MetadataRoute.Robots {\n+ return {\n+ rules: { userAgent: '*', allow: '/' },\n+ sitemap: `${siteConfig.url}/sitemap.xml`,\n+ };\n+}", "status": "added"}, {"additions": 23, "deletions": 0, "filename": "app/sitemap.ts", "patch": "@@ -0,0 +1,23 @@\n+import { source, changelogSource } from '@/lib/source';\n+import { siteConfig } from '@/lib/config';\n+import type { MetadataRoute } from 'next';\n+\n+export const dynamic = 'force-static';\n+\n+const BASE_URL = siteConfig.url;\n+\n+export default function sitemap(): MetadataRoute.Sitemap {\n+ return [\n+ { url: BASE_URL, lastModified: new Date(), priority: 1.0 },\n+ ...source.getPages().map((page) => ({\n+ url: `${BASE_URL}${page.url}`,\n+ lastModified: new Date(),\n+ priority: 0.7,\n+ })),\n+ ...changelogSource.getPages().map((page) => ({\n+ url: `${BASE_URL}${page.url}`,\n+ lastModified: new Date(),\n+ priority: 0.5,\n+ })),\n+ ];\n+}", "status": "added"}, {"additions": 1, "deletions": 1, "filename": "content/docs/analytics/partner-marketing-reports.mdx", "patch": "@@ -47,7 +47,7 @@ To preview an existing Partner Report click **Actions > View** from the reports\n \n \n \n-Marketing partner users added to partner reports are able to access their customized reporting views by logging into Next Commerce at [**accounts.29next.com**](https://acccounts.29next.com).\n+Marketing partner users added to partner reports are able to access their customized reporting views by logging into Next Commerce at [**accounts.29next.com**](https://accounts.29next.com).\n \n Individual users can be invited to multiple partner reports, across multiple stores, from the same Next Commerce account.\n ", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "package.json", "patch": "@@ -9,7 +9,8 @@\n \"start\": \"next start\",\n \"lint\": \"next lint\",\n \"validate-links\": \"node scripts/validate-links.mjs\",\n- \"audit-developer-links\": \"node scripts/audit-developer-links.mjs\"\n+ \"audit-developer-links\": \"node scripts/audit-developer-links.mjs\",\n+ \"check-search-budget\": \"node scripts/check-search-budget.mjs\"\n },\n \"dependencies\": {\n \"@next/third-parties\": \"^16.3.1\",", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "public/_headers", "patch": "@@ -0,0 +1,2 @@\n+/api/search\n+ Cache-Control: public, max-age=3600, stale-while-revalidate=86400", "status": "added"}, {"additions": 31, "deletions": 0, "filename": "scripts/check-search-budget.mjs", "patch": "@@ -0,0 +1,31 @@\n+// Fails the build when the static Orama search index (served at /api/search)\n+// grows past the budget. Every visitor downloads this file on first search,\n+// so keep it bounded.\n+import { statSync, existsSync } from 'node:fs';\n+import { join, dirname } from 'node:path';\n+import { fileURLToPath } from 'node:url';\n+\n+const SEARCH_INDEX_BUDGET_BYTES = 6_000_000;\n+\n+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..');\n+const candidates = [\n+ join(repoRoot, 'out', 'api', 'search'),\n+ join(repoRoot, 'out', 'api', 'search.body'),\n+ join(repoRoot, 'out', 'api', 'search', 'index.json'),\n+ join(repoRoot, 'out', 'api', 'search', 'index'),\n+];\n+\n+const indexPath = candidates.find((p) => existsSync(p) && statSync(p).isFile());\n+if (!indexPath) {\n+ console.error(`check-search-budget: no built search index found. Looked at:\\n ${candidates.join('\\n ')}\\nRun \\`npm run build\\` first.`);\n+ process.exit(1);\n+}\n+\n+const size = statSync(indexPath).size;\n+const mb = (n) => (n / 1_000_000).toFixed(2);\n+const overBudget = size > SEARCH_INDEX_BUDGET_BYTES;\n+\n+console.log(\n+ `check-search-budget: ${indexPath.replace(repoRoot + '/', '')} is ${size} bytes (${mb(size)} MB); budget ${SEARCH_INDEX_BUDGET_BYTES} bytes (${mb(SEARCH_INDEX_BUDGET_BYTES)} MB) — ${overBudget ? 'OVER BUDGET' : 'ok'}`,\n+);\n+process.exit(overBudget ? 1 : 0);", "status": "added"}], "message": "Agent entry surfaces: sitemap, robots, custom 404, search index budget\n\n- app/sitemap.ts + app/robots.ts: static sitemap over docs and changelog\n pages, declared in robots (site had neither).\n- app/not-found.tsx: 404 with recovery links to docs, search, changelog,\n developer docs, and /llms.txt.\n- public/_headers: 1h cache with stale-while-revalidate on the 4.85 MB\n /api/search index (was max-age=0).\n- scripts/check-search-budget.mjs + CI step: fail when the built index\n exceeds 6 MB.\n- Fix acccounts.29next.com typo in partner marketing reports.\n\nCo-Authored-By: Claude Fable 5.1 ", "sha": "ac14050718109b3128d2cd508175a0c33245e54d"}], "post_review_commits": ["26173bcdcdd7a135a6ca889c532129b9cb5ec36d", "81300ecdea8d37ec4bf48f533164534ccc0af294"], "pr_author": "next-devin", "pr_title": "Agent entry surfaces: sitemap, robots, custom 404, search index budget", "repo_name": "NextCommerceCo/docs"}, "repo": "NextCommerceCo/docs", "snapshot": "snapshots/033613e7c812ebcba4841a8327cbbbe651df90a8700e0be7bab841b261f96f32.pack", "split": "eval", "task_id": "0f048a85ac719cd17cb8faa63e592dcc8f41471b0b0ac9f6ae7ef128db90ed2b"} {"base_sha": "28e804aa4f5c7cc2c771406bbf193001b7d84ffa", "cohort": "all_three_tool_loops", "context": {"canonical_pr_url": "https://github.com/spencerjireh/cujo/pull/17", "id": "11f19ec014da9511dfb8c6d5de7c1093f2c2e07eb8fbc5c84b91b5e0163b8005", "preparation_mode": "source-only", "snapshot": {"base_ref": "28e804aa4f5c7cc2c771406bbf193001b7d84ffa", "base_sha": "28e804aa4f5c7cc2c771406bbf193001b7d84ffa", "body": "", "head_ref": "272d8d49f35dd8c6c22e6ce91bb73ac993ccc616", "head_sha": "272d8d49f35dd8c6c22e6ce91bb73ac993ccc616", "name": "cujo", "number": 17, "owner": "spencerjireh", "pr_url": "https://github.com/spencerjireh/cujo/pull/17", "title": ""}}, "head_sha": "272d8d49f35dd8c6c22e6ce91bb73ac993ccc616", "metadata": {"group_id": "0d8cd33588b7468617c1943d388ac4edb23f4f06c8f5b0660872b34a342b6041", "snapshot": {"base_sha": "28e804aa4f5c7cc2c771406bbf193001b7d84ffa", "external_requirements": [], "head_sha": "272d8d49f35dd8c6c22e6ce91bb73ac993ccc616", "objects": 242, "objects_sha256": "75c7c2ba4e8ed21b1bf24309ec5ac7ef39a084a34aac7c4c60a590de421a5cda", "patch_sha256": "6078e2bdbffac2e04adcb9b113785bc93fbe107902791b3b766bbbc9c7ddf892"}}, "pr_number": 17, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "fc825b03ffb1", "description": "The notifier trusted an existing channel binding without rechecking the repo's declaration, so removing or changing `discord_guild` did not stop review delivery or clear the stale binding.", "file_path": "apps/cujo/src/notifier.ts"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "fc825b03ffb1", "description": "A failed GitHub read was treated as a missing `discord_guild` declaration. This made an outage indistinguishable from revocation and could incorrectly stop delivery; commands also gave a misleading refusal instead of asking the user to retry.", "file_path": "apps/cujo/src/github.ts"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "fc825b03ffb1", "description": "`/cujo unwatch` required current authorization and an installed repo, so a server could not remove its own binding after the repo revoked its declaration or the GitHub App was uninstalled.", "file_path": "apps/cujo/src/interactions.ts"}, {"action_id": "A4", "action_type": "fix", "category": "security", "commit_sha": "fc825b03ffb1", "description": "The authorization recheck immediately before writing a watch binding reused a 30-second cached declaration, allowing a declaration revoked during the command to still authorize the binding.", "file_path": "apps/cujo/src/interactions.ts"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "fc825b03ffb1", "description": "The default branch name was inserted unencoded into the GitHub contents URL's `ref` query parameter. Characters such as `#` or `&` could truncate or alter the ref, causing an incorrect declaration read.", "file_path": "apps/cujo/src/github.ts"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "fc825b03ffb1", "description": "The `discord_guild` parser did not match declarations in CRLF-terminated `.cujo.yml` files, silently treating Windows-written configurations as undeclared.", "file_path": "apps/cujo/src/github.ts"}, {"action_id": "A7", "action_type": "improvement", "category": "documentation", "commit_sha": "fc825b03ffb1", "description": "The contributor guidance did not explain that a declaration merged to the repo's default branch is the normal authority for allowing a Discord server, making it appear to bypass the operator API.", "file_path": "CONTRIBUTING.md"}, {"action_id": "A8", "action_type": "improvement", "category": "documentation", "commit_sha": "fc825b03ffb1", "description": "The review standards omitted the repo-declaration authorization path and its trusted-side GitHub App read requirement, leaving the bot's guidance inconsistent with the intended authority model.", "file_path": "best_practices.md"}], "commits_under_review": [{"author": "spencerjireh", "date": "2026-08-28T01:23:50Z", "files": [{"additions": 65, "deletions": 0, "filename": "apps/cujo/src/authorization.ts", "patch": "@@ -0,0 +1,65 @@\n+/**\n+ * May this Discord server manage this repo's review notifications\n+ * (spec Contract 8)?\n+ *\n+ * The answer comes from the repository first. A repo names its server in\n+ * `.cujo.yml` on the default branch, which makes the authority repo write\n+ * access — the thing that actually correlates with owning the repo — rather\n+ * than \"someone holds a Cujo login\". It is self-serve, auditable in git\n+ * history, and revoked by a commit (decision 31).\n+ *\n+ * The operator table stays as an override, for moving a repo between servers\n+ * or allowing one whose `.cujo.yml` cannot be changed.\n+ *\n+ * Neither half alone does anything: the server still has to run `/cujo watch`.\n+ * Without the repo's declaration anyone could point your repo's reviews at\n+ * their channel; without the server's command anyone could spam a server they\n+ * do not belong to.\n+ */\n+\n+import type { GitHubReader } from \"./github\";\n+import type { Store } from \"./store\";\n+\n+export type Authorization =\n+ | { allowed: true; source: \"repo\" | \"operator\" }\n+ | { allowed: false; reason: \"not_declared\" | \"declared_elsewhere\" };\n+\n+export interface AuthorizationDeps {\n+ store: Store;\n+ github: GitHubReader;\n+}\n+\n+export async function authorizationFor(\n+ deps: AuthorizationDeps,\n+ guildId: string,\n+ repo: string,\n+): Promise {\n+ if (deps.store.isGuildAuthorized(guildId, repo)) return { allowed: true, source: \"operator\" };\n+ const declared = await deps.github.declaredGuild(repo);\n+ if (declared === guildId) return { allowed: true, source: \"repo\" };\n+ // A repo that named a different server is a different message from one that\n+ // named none: the first is someone else's, the second is a missing line.\n+ return { allowed: false, reason: declared ? \"declared_elsewhere\" : \"not_declared\" };\n+}\n+\n+/**\n+ * What to tell the person who ran the command. A refusal that does not say how\n+ * to fix it just sends them to find an operator, which is the errand this\n+ * whole change removes.\n+ */\n+export function explain(\n+ repo: string,\n+ guildId: string,\n+ authorization: Authorization & { allowed: false },\n+): string {\n+ if (authorization.reason === \"declared_elsewhere\") {\n+ return `\\`${repo}\\` names a different Discord server in its \\`.cujo.yml\\`. Change it there, or ask a Cujo operator to move it.`;\n+ }\n+ return [\n+ `\\`${repo}\\` has not named this server. Add this to \\`.cujo.yml\\` on its default branch:`,\n+ \"```yaml\",\n+ `discord_guild: \"${guildId}\"`,\n+ \"```\",\n+ \"Merging that is what proves you control the repo.\",\n+ ].join(\"\\n\");\n+}", "status": "added"}, {"additions": 74, "deletions": 1, "filename": "apps/cujo/src/github.test.ts", "patch": "@@ -7,7 +7,7 @@ vi.mock(\"@cujo/gh-app-auth\", () => ({\n getAppJwt: vi.fn(async () => \"app_jwt\"),\n }));\n \n-import { GitHubReader } from \"./github\";\n+import { GitHubReader, parseDeclaredGuild } from \"./github\";\n \n type Route = (url: URL) => { status?: number; body: unknown };\n \n@@ -97,6 +97,79 @@ describe(\"GitHubReader.alreadyReviewed\", () => {\n });\n });\n \n+describe(\"parseDeclaredGuild\", () => {\n+ it(\"reads the key whether or not it is quoted, and ignores a trailing comment\", () => {\n+ expect(parseDeclaredGuild('discord_guild: \"222222222222222222\"')).toBe(\"222222222222222222\");\n+ expect(parseDeclaredGuild(\"discord_guild: 222222222222222222\")).toBe(\"222222222222222222\");\n+ expect(parseDeclaredGuild(\"discord_guild: '222222222222222222' # ours\")).toBe(\n+ \"222222222222222222\",\n+ );\n+ expect(parseDeclaredGuild(\"test: uv run pytest\\ndiscord_guild: 222222222222222222\\n\")).toBe(\n+ \"222222222222222222\",\n+ );\n+ });\n+\n+ it(\"ignores anything that is not a top-level snowflake\", () => {\n+ // Not a snowflake, so not a declaration. That is the whole validation.\n+ expect(parseDeclaredGuild(\"discord_guild: not-an-id\")).toBeNull();\n+ expect(parseDeclaredGuild(\"discord_guild: 12\")).toBeNull();\n+ expect(parseDeclaredGuild(\"\")).toBeNull();\n+ expect(parseDeclaredGuild(\"install: uv sync\")).toBeNull();\n+ // Nested under another key is not the top level.\n+ expect(parseDeclaredGuild(\"smoke:\\n discord_guild: 222222222222222222\")).toBeNull();\n+ // A near-miss key name must not match.\n+ expect(parseDeclaredGuild(\"my_discord_guild: 222222222222222222\")).toBeNull();\n+ });\n+});\n+\n+describe(\"GitHubReader.declaredGuild\", () => {\n+ function fakeConfigFetch(file: { status: number; body: string }) {\n+ const paths: string[] = [];\n+ const impl = vi.fn(async (input: string | URL | Request) => {\n+ const url = new URL(String(input));\n+ paths.push(`${url.pathname}${url.search}`);\n+ if (url.pathname === \"/repos/o/r\") {\n+ return new Response(JSON.stringify({ default_branch: \"trunk\" }), { status: 200 });\n+ }\n+ return new Response(file.body, { status: file.status });\n+ });\n+ return { impl: impl as unknown as typeof fetch, paths, calls: impl };\n+ }\n+\n+ it(\"reads .cujo.yml from the default branch, not from a pull request\", async () => {\n+ const { impl, paths } = fakeConfigFetch({\n+ status: 200,\n+ body: 'discord_guild: \"222222222222222222\"\\n',\n+ });\n+ const reader = new GitHubReader(\"1\", \"pem\", impl);\n+ expect(await reader.declaredGuild(\"o/r\")).toBe(\"222222222222222222\");\n+ // The declaration has to be merged, which is what makes it proof.\n+ expect(paths).toContain(\"/repos/o/r/contents/.cujo.yml?ref=trunk\");\n+ });\n+\n+ it(\"is null when the repo has no .cujo.yml\", async () => {\n+ const { impl } = fakeConfigFetch({ status: 404, body: \"{}\" });\n+ expect(await new GitHubReader(\"1\", \"pem\", impl).declaredGuild(\"o/r\")).toBeNull();\n+ });\n+\n+ it(\"is null rather than throwing when GitHub refuses\", async () => {\n+ const { impl } = fakeConfigFetch({ status: 500, body: \"{}\" });\n+ expect(await new GitHubReader(\"1\", \"pem\", impl).declaredGuild(\"o/r\")).toBeNull();\n+ });\n+\n+ it(\"caches, so a status command does not re-read for every repo\", async () => {\n+ const { impl, calls } = fakeConfigFetch({\n+ status: 200,\n+ body: \"discord_guild: 222222222222222222\",\n+ });\n+ const reader = new GitHubReader(\"1\", \"pem\", impl);\n+ await reader.declaredGuild(\"o/r\");\n+ const after = calls.mock.calls.length;\n+ await reader.declaredGuild(\"o/r\");\n+ expect(calls.mock.calls.length).toBe(after);\n+ });\n+});\n+\n describe(\"GitHubReader.installedRepos\", () => {\n /** The App JWT and an installation token authenticate different calls here. */\n function fakeAppFetch(repos: string[]) {", "status": "modified"}, {"additions": 59, "deletions": 0, "filename": "apps/cujo/src/github.ts", "patch": "@@ -22,6 +22,20 @@ const API = \"https://api.github.com\";\n const REPO_CACHE_MS = 60_000;\n /** The same bound the PR reads use: enough for any real account, and finite. */\n const MAX_PAGES = 30;\n+/** Short: a repo that just declared a server should not wait to be believed. */\n+const GUILD_CACHE_MS = 30_000;\n+\n+/**\n+ * Pull `discord_guild` out of a `.cujo.yml` without parsing YAML. One key, one\n+ * shape — a Discord snowflake at the top level — so a strict line match reads\n+ * it and anything else simply does not match, which is the \"ignored, and said\n+ * so in `/cujo status`\" behaviour Contract 8 asks for. A YAML dependency for\n+ * one scalar is not worth the bundle or the parser's own surface.\n+ */\n+export function parseDeclaredGuild(yaml: string): string | null {\n+ const match = /^discord_guild:[ \\t]*[\"']?(\\d{17,20})[\"']?[ \\t]*(?:#.*)?$/m.exec(yaml);\n+ return match?.[1] ?? null;\n+}\n \n /**\n * The read side of the GitHub App: PR metadata, changed files, and the\n@@ -31,6 +45,7 @@ export class GitHubReader {\n private readonly privateKey: string;\n private repoCache: { repos: string[]; expiresAt: number } | null = null;\n private repoScan: Promise | null = null;\n+ private readonly guildCache = new Map();\n \n constructor(\n private readonly appId: string,\n@@ -175,6 +190,50 @@ export class GitHubReader {\n }\n }\n \n+ /**\n+ * The Discord server a repo declares in `.cujo.yml` on its default branch\n+ * (Contract 8). Null when the file is absent, unreadable, or carries no\n+ * usable `discord_guild`.\n+ *\n+ * Read here, through the App, and never from the sandbox's copy: the sandbox\n+ * holds the pull request's code, and code that declares its own authorization\n+ * is not an authorization at all.\n+ *\n+ * The default branch, not the pull request's: declaring a server is an act\n+ * that has to be merged, which is exactly what makes it proof of control.\n+ */\n+ async declaredGuild(repo: string): Promise {\n+ const cached = this.guildCache.get(repo);\n+ if (cached && cached.expiresAt > Date.now()) return cached.guildId;\n+ let guildId: string | null = null;\n+ try {\n+ const { default_branch } = await this.get<{ default_branch: string }>(repo, `/repos/${repo}`);\n+ const yaml = await this.rawFile(repo, \".cujo.yml\", default_branch);\n+ guildId = yaml === null ? null : parseDeclaredGuild(yaml);\n+ } catch (error) {\n+ // A repo with no `.cujo.yml`, or a GitHub hiccup. Both mean \"not\n+ // declared\" for now; the caller says so rather than guessing.\n+ console.warn(`github: could not read .cujo.yml for ${repo}`, error);\n+ guildId = null;\n+ }\n+ this.guildCache.set(repo, { guildId, expiresAt: Date.now() + GUILD_CACHE_MS });\n+ return guildId;\n+ }\n+\n+ /** A file's bytes at a ref, or null when it is not there. */\n+ private async rawFile(repo: string, path: string, ref: string): Promise {\n+ const res = await this.fetchImpl(`${API}/repos/${repo}/contents/${path}?ref=${ref}`, {\n+ headers: {\n+ authorization: `Bearer ${await this.token(repo)}`,\n+ accept: \"application/vnd.github.raw\",\n+ \"user-agent\": \"cujo\",\n+ },\n+ });\n+ if (res.status === 404) return null;\n+ if (!res.ok) throw new Error(`GitHub /repos/${repo}/contents/${path} returned ${res.status}`);\n+ return res.text();\n+ }\n+\n /** Contract 5: skip the turn when the bot already reviewed this head SHA. */\n async alreadyReviewed(repo: string, prNumber: number, headSha: string): Promise {\n for (let page = 1; page <= 30; page++) {", "status": "modified"}, {"additions": 111, "deletions": 15, "filename": "apps/cujo/src/interactions.test.ts", "patch": "@@ -59,11 +59,19 @@ function fakeDiscord(overrides: Record = {}) {\n };\n }\n \n-function build(options: { discord?: Record; repos?: string[] } = {}) {\n+function build(\n+ options: {\n+ discord?: Record;\n+ repos?: string[];\n+ /** What the repo names in its `.cujo.yml`; null is \"no declaration\". */\n+ declaredGuild?: string | null;\n+ } = {},\n+) {\n const store = new Store(\":memory:\");\n const discord = fakeDiscord(options.discord);\n const github = {\n installedRepos: vi.fn(async () => options.repos ?? [\"spencerjireh/orders-api\"]),\n+ declaredGuild: vi.fn(async () => options.declaredGuild ?? null),\n };\n const settled: ((name: string) => void)[] = [];\n const nextSettled = () => new Promise((resolve) => settled.push(resolve));\n@@ -194,7 +202,22 @@ describe(\"interactions endpoint\", () => {\n });\n });\n \n- it(\"refuses a repo this server was never authorized for\", async () => {\n+ it(\"watches a repo that named this server, with no operator involved\", async () => {\n+ const built = build({ declaredGuild: GUILD });\n+ const content = await reply(\n+ built,\n+ command(\"watch\", [\n+ { name: \"repo\", type: 3, value: \"spencerjireh/orders-api\" },\n+ { name: \"channel\", type: 7, value: CHANNEL },\n+ ]),\n+ );\n+ expect(content).toContain(`<#${CHANNEL}>`);\n+ expect(built.store.getDiscordChannel(\"spencerjireh/orders-api\")?.guildId).toBe(GUILD);\n+ // Nothing was written to the operator table to make this work.\n+ expect(built.store.listGuildRepos()).toHaveLength(0);\n+ });\n+\n+ it(\"tells a server that has not been named exactly what to add, and where\", async () => {\n const built = build();\n const content = await reply(\n built,\n@@ -203,11 +226,38 @@ describe(\"interactions endpoint\", () => {\n { name: \"channel\", type: 7, value: CHANNEL },\n ]),\n );\n- expect(content).toContain(\"not authorized\");\n+ expect(content).toContain(\".cujo.yml\");\n+ expect(content).toContain(`discord_guild: \"${GUILD}\"`);\n expect(built.store.getDiscordChannel(\"spencerjireh/orders-api\")).toBeNull();\n expect(built.discord.getChannel).not.toHaveBeenCalled();\n });\n \n+ it(\"says so plainly when the repo named a different server\", async () => {\n+ const built = build({ declaredGuild: \"999999999999999999\" });\n+ const content = await reply(\n+ built,\n+ command(\"watch\", [\n+ { name: \"repo\", type: 3, value: \"spencerjireh/orders-api\" },\n+ { name: \"channel\", type: 7, value: CHANNEL },\n+ ]),\n+ );\n+ expect(content).toContain(\"a different Discord server\");\n+ expect(built.store.getDiscordChannel(\"spencerjireh/orders-api\")).toBeNull();\n+ });\n+\n+ it(\"still honours an operator's allowance when the repo declares nothing\", async () => {\n+ const built = build();\n+ authorize(built.store);\n+ const content = await reply(\n+ built,\n+ command(\"watch\", [\n+ { name: \"repo\", type: 3, value: \"spencerjireh/orders-api\" },\n+ { name: \"channel\", type: 7, value: CHANNEL },\n+ ]),\n+ );\n+ expect(content).toContain(`<#${CHANNEL}>`);\n+ });\n+\n it(\"checks Manage Server itself, not only through Discord's own gate\", async () => {\n const built = build();\n authorize(built.store);\n@@ -311,7 +361,23 @@ describe(\"interactions endpoint\", () => {\n const content = await reply(built, command(\"status\"));\n expect(content).toContain(`spencerjireh/orders-api\\` → <#${CHANNEL}>`);\n expect(content).toContain(`<@&${ROLE}>`);\n- expect(content).toContain(\"other-repo` — authorized, not being sent anywhere\");\n+ expect(content).toContain(\"other-repo` — allowed, not being sent anywhere\");\n+ // It cannot list every repo that named this server without reading each\n+ // one's .cujo.yml, so it says how to add one instead.\n+ expect(content).toContain(`discord_guild: \"${GUILD}\"`);\n+ });\n+\n+ it(\"lists a repo watched here even when no operator allowed it\", async () => {\n+ const built = build({ declaredGuild: GUILD });\n+ built.store.putDiscordChannel({\n+ repo: \"spencerjireh/orders-api\",\n+ channelId: CHANNEL,\n+ guildId: GUILD,\n+ channelName: \"reviews\",\n+ notifyRoleId: null,\n+ });\n+ const content = await reply(built, command(\"status\"));\n+ expect(content).toContain(`spencerjireh/orders-api\\` → <#${CHANNEL}>`);\n });\n \n it(\"posts a sample card, and reports a channel it cannot post to\", async () => {\n@@ -339,9 +405,8 @@ describe(\"interactions endpoint\", () => {\n expect(failed).toContain(\"could not post\");\n });\n \n- it(\"completes the repo box from the repos this server may watch\", async () => {\n+ it(\"completes the repo box from every repo Cujo could review\", async () => {\n const built = build({ repos: [\"spencerjireh/orders-api\", \"spencerjireh/other\"] });\n- authorize(built.store);\n const res = await post(built.app, {\n type: 4,\n application_id: \"app1\",\n@@ -353,22 +418,35 @@ describe(\"interactions endpoint\", () => {\n expect(res.status).toBe(200);\n const body = (await res.json()) as { type: number; data: { choices: { value: string }[] } };\n expect(body.type).toBe(8);\n- // `other` is installed but not authorized here, so it is not offered.\n- expect(body.data.choices.map((c) => c.value)).toEqual([\"spencerjireh/orders-api\"]);\n+ // Narrowing by authorization would mean one .cujo.yml read per repo, per\n+ // keystroke. `watch` refuses with the fix instead.\n+ expect(body.data.choices.map((c) => c.value)).toEqual([\n+ \"spencerjireh/orders-api\",\n+ \"spencerjireh/other\",\n+ ]);\n+ expect(built.github.declaredGuild).not.toHaveBeenCalled();\n });\n \n- it(\"offers nothing to a server with no authorization\", async () => {\n- const built = build();\n+ it(\"narrows the box as the invoker types\", async () => {\n+ const built = build({ repos: [\"spencerjireh/orders-api\", \"spencerjireh/other\"] });\n const res = await post(built.app, {\n type: 4,\n application_id: \"app1\",\n token: \"tok\",\n guild_id: GUILD,\n- data: { name: \"cujo\", options: [{ type: 1, name: \"watch\", options: [] }] },\n+ data: {\n+ name: \"cujo\",\n+ options: [\n+ {\n+ type: 1,\n+ name: \"watch\",\n+ options: [{ name: \"repo\", type: 3, value: \"orders\", focused: true }],\n+ },\n+ ],\n+ },\n });\n- const body = (await res.json()) as { data: { choices: unknown[] } };\n- expect(body.data.choices).toEqual([]);\n- expect(built.github.installedRepos).not.toHaveBeenCalled();\n+ const body = (await res.json()) as { data: { choices: { value: string }[] } };\n+ expect(body.data.choices.map((c) => c.value)).toEqual([\"spencerjireh/orders-api\"]);\n });\n \n it(\"falls back to what it knows when GitHub cannot be reached\", async () => {\n@@ -439,7 +517,25 @@ describe(\"interactions endpoint\", () => {\n { name: \"channel\", type: 7, value: CHANNEL },\n ]),\n );\n- expect(content).toContain(\"no longer authorized\");\n+ expect(content).toContain(\"no longer allowed\");\n+ expect(built.store.getDiscordChannel(\"spencerjireh/orders-api\")).toBeNull();\n+ });\n+\n+ it(\"re-checks a repo declaration reverted during the Discord round trips\", async () => {\n+ const built = build({ declaredGuild: GUILD });\n+ built.discord.listRoles.mockImplementationOnce(async () => {\n+ // The declaration was reverted on the default branch mid-command.\n+ built.github.declaredGuild.mockResolvedValue(null);\n+ return [{ id: GUILD, name: \"@everyone\", permissions: CAN_POST }];\n+ });\n+ const content = await reply(\n+ built,\n+ command(\"watch\", [\n+ { name: \"repo\", type: 3, value: \"spencerjireh/orders-api\" },\n+ { name: \"channel\", type: 7, value: CHANNEL },\n+ ]),\n+ );\n+ expect(content).toContain(\"no longer allowed\");\n expect(built.store.getDiscordChannel(\"spencerjireh/orders-api\")).toBeNull();\n });\n ", "status": "modified"}, {"additions": 42, "deletions": 32, "filename": "apps/cujo/src/interactions.ts", "patch": "@@ -15,6 +15,7 @@\n \n import { createPublicKey, verify as verifySignature } from \"node:crypto\";\n import { Hono } from \"hono\";\n+import { authorizationFor, explain } from \"./authorization\";\n import {\n GUILD_ANNOUNCEMENT,\n GUILD_TEXT,\n@@ -157,12 +158,21 @@ export function interactionRoutes(deps: InteractionDeps): Hono {\n const repo = optionValue(command, \"repo\");\n if (!repo || !REPO.test(repo)) return \"That does not look like an `owner/name` repository.\";\n const normalized = repo.toLowerCase();\n- if (!deps.store.isGuildAuthorized(guildId, normalized)) {\n- // Which repos a server may reach is an operator's decision, made over\n- // the Access-gated API where it carries an email (decision 28).\n- return `This server is not authorized for \\`${normalized}\\`. A Cujo operator has to allow it first.`;\n+\n+ // Checked before authorization so the refusal names the real problem: a\n+ // repo the App cannot see has no readable `.cujo.yml` either, and \"it has\n+ // not named this server\" would send someone editing a file that Cujo could\n+ // not read anyway. Only a list Cujo actually read can refuse.\n+ const installed = await deps.github.installedRepos().catch(() => null);\n+ if (installed && !installed.some((full) => full.toLowerCase() === normalized)) {\n+ return `Cujo's GitHub App is not installed on \\`${normalized}\\`, so it would never have anything to send.`;\n }\n \n+ // The repo says which server may have its reviews; the server says which\n+ // channel. Both halves are needed (decision 31).\n+ const authorization = await authorizationFor(deps, guildId, normalized);\n+ if (!authorization.allowed) return explain(normalized, guildId, authorization);\n+\n if (command?.name === \"unwatch\") {\n // A binding is global to the repo, so a server may only take down its\n // own: otherwise one authorized server could silence another's reviews.\n@@ -249,8 +259,6 @@ async function repoChoices(\n ): Promise<{ name: string; value: string }[]> {\n const guildId = interaction.guild_id;\n if (!guildId) return [];\n- const authorized = new Set(deps.store.listGuildRepos(guildId).map((a) => a.repo));\n- if (authorized.size === 0) return [];\n let installed: string[];\n try {\n installed = await Promise.race([\n@@ -263,13 +271,16 @@ async function repoChoices(\n console.error(\"discord: could not list installed repos\", error);\n installed = [];\n }\n- // A cold cache or a GitHub hiccup falls back to what Cujo already knows,\n- // rather than showing an empty picker.\n- const candidates = installed.length > 0 ? installed : [...authorized];\n+ // Everything Cujo could review, not everything this server may watch:\n+ // narrowing by authorization would mean reading each repo's `.cujo.yml` on\n+ // every keystroke. `watch` does one targeted read and says exactly what to\n+ // add if the repo has not named this server, which teaches more than a\n+ // missing row in a dropdown.\n+ const known = new Set(deps.store.listGuildRepos(guildId).map((a) => a.repo));\n+ const candidates = installed.length > 0 ? installed : [...known];\n const typed = focusedValue(interaction).toLowerCase();\n return (\n candidates\n- .filter((repo) => authorized.has(repo.toLowerCase()))\n .filter((repo) => repo.toLowerCase().includes(typed))\n // A choice value must be the exact repo, and Discord caps it at 100\n // characters, so a longer name cannot be offered — it can still be\n@@ -280,20 +291,28 @@ async function repoChoices(\n );\n }\n \n+/**\n+ * What this server is sending, plus anything an operator allowed that is not\n+ * being sent yet. It does not try to enumerate every repo that named this\n+ * server: that would be one `.cujo.yml` read per installed repo, so the\n+ * closing line says how to add one instead.\n+ */\n function status(deps: InteractionDeps, guildId: string): string {\n- const authorizations = deps.store.listGuildRepos(guildId);\n- if (authorizations.length === 0) {\n- return \"This server is not authorized for any repository yet.\";\n+ const repos = new Set(deps.store.listGuildRepos(guildId).map((a) => a.repo));\n+ for (const binding of deps.store.listDiscordChannels()) {\n+ if (binding.guildId === guildId) repos.add(binding.repo);\n }\n- const lines = authorizations.map((authorization) => {\n- const binding = deps.store.getDiscordChannel(authorization.repo);\n+ const lines = [...repos].sort().map((repo) => {\n+ const binding = deps.store.getDiscordChannel(repo);\n if (!binding || binding.guildId !== guildId) {\n- return `• \\`${authorization.repo}\\` — authorized, not being sent anywhere`;\n+ return `• \\`${repo}\\` — allowed, not being sent anywhere`;\n }\n const role = binding.notifyRoleId ? `, pinging <@&${binding.notifyRoleId}>` : \"\";\n- return `• \\`${authorization.repo}\\` → <#${binding.channelId}>${role}`;\n+ return `• \\`${repo}\\` → <#${binding.channelId}>${role}`;\n });\n- return fitLines(lines);\n+ const hint = `Any repo whose \\`.cujo.yml\\` says \\`discord_guild: \"${guildId}\"\\` can be watched here.`;\n+ if (lines.length === 0) return `Nothing is being sent to this server yet. ${hint}`;\n+ return fitLines([...lines, \"\", hint]);\n }\n \n /**\n@@ -330,15 +349,6 @@ async function watch(\n return `\\`${input.repo}\\` is already being sent to another server. A Cujo operator can move it.`;\n }\n \n- // A repo the App is not installed on can be bound and then never notified,\n- // which is the silent failure the rest of this route exists to prevent. Only\n- // refuse on a list Cujo actually managed to read: GitHub being down is not a\n- // reason to block a bind.\n- const installed = await deps.github.installedRepos().catch(() => null);\n- if (installed && !installed.some((repo) => repo.toLowerCase() === input.repo)) {\n- return `Cujo's GitHub App is not installed on \\`${input.repo}\\`, so it would never have anything to send.`;\n- }\n-\n const channel = await deps.discord.getChannel(channelId).catch(() => null);\n if (!channel) return \"Cujo cannot see that channel.\";\n if (channel.type !== GUILD_TEXT && channel.type !== GUILD_ANNOUNCEMENT) {\n@@ -367,11 +377,11 @@ async function watch(\n }\n \n // Re-checked here, not only at the top: the Discord round trips above are\n- // awaits, and an operator revoking this server in the meantime must not end\n- // with a binding written for a server that may no longer see the repo.\n- if (!deps.store.isGuildAuthorized(input.guildId, input.repo)) {\n- return `This server is no longer authorized for \\`${input.repo}\\`.`;\n- }\n+ // awaits, and a declaration reverted or an operator's allowance withdrawn in\n+ // the meantime must not end with a binding for a server that may no longer\n+ // see the repo.\n+ const still = await authorizationFor(deps, input.guildId, input.repo);\n+ if (!still.allowed) return `This server is no longer allowed to watch \\`${input.repo}\\`.`;\n deps.store.putDiscordChannel({\n repo: input.repo,\n channelId,", "status": "modified"}], "message": "feat(cujo): let a repo name its own Discord server in .cujo.yml\n\nDecision 28 made a Cujo operator vouch that a Discord server may see a repo.\nThat was wrong twice over: a Cujo operator is not necessarily anyone who owns\nthe repo, so the check confirmed the wrong fact, and every repo needed a human\nwith an Access login to run a request by hand -- in practice a `curl`.\n\nA repo now names its server itself, with `discord_guild` in `.cujo.yml` on the\ndefault branch. The authority becomes repo write access, which is what actually\ncorrelates with owning a repo. It is self-serve for any number of repos,\nauditable in git history like any other config change, and revoked by a commit\nrather than by finding whoever holds a Cujo login.\n\nThe handshake stays two-sided. The repo's declaration alone would let anyone\nroute a repo they do not own; the server's `/cujo watch` alone would let anyone\nsend a repo's reviews into a server they do not belong to.\n\nRead trusted-side, through the App, from the default branch. Never the\nsandbox's copy: the sandbox holds the pull request's code, and code that\ndeclares its own authorization is not an authorization. Reading the default\nbranch rather than the pull request's is also what makes it proof -- it has to\nbe merged.\n\nThe key is extracted with one strict pattern rather than parsed as YAML. It has\none shape, a snowflake at the top level, so anything else does not match and\nthe repo counts as undeclared; a YAML dependency for one scalar is not worth\nthe bundle or the parser's own surface. A wrong declaration never costs a\nreview: `watch` prints the exact line to add and `status` closes with it.\n\nAutocomplete stops narrowing to what a server may watch. Doing that now means\none `.cujo.yml` read per installed repo per keystroke against a three-second\nbudget, so it offers everything the App is installed on and the refusal carries\nthe fix -- which teaches more than a row missing from a dropdown anyway. The\ninstalled-repo check moved ahead of the authorization check for the same\nreason: a repo the App cannot see has no readable `.cujo.yml` either, and \"it\nhas not named this server\" would send someone to edit a file Cujo could not\nhave read.\n\nThe operator route survives as an override, for moving a repo between servers\nor for a repo whose `.cujo.yml` cannot be changed.\n\nClaude-Session: https://claude.ai/code/session_01EUqoBcrZVQSDEYngwih2hv", "sha": "222afeaad290a517f3644884094712edc56548bb"}, {"author": "spencerjireh", "date": "2026-08-28T01:24:01Z", "files": [{"additions": 5, "deletions": 3, "filename": "AGENTS.md", "patch": "@@ -85,9 +85,11 @@ thing GitHub touches:\n deployed database.\n - `interactions.ts` serves the `/cujo` slash command on the **webhook** host,\n Ed25519-verified (spec Contract 8); `discord-commands.ts` is the command\n- definition. A server picks its own channel and role; which repos it may reach\n- is authorized by an operator over the Access-gated API. Nothing here approves\n- a review, and it must not grow that (decision 28).\n+ definition. `authorization.ts` answers whether a server may watch a repo: the\n+ repo names it in `.cujo.yml` on the default branch, read trusted-side through\n+ the App and never from the sandbox, with the operator API as an override\n+ (decision 31). Nothing here approves a review, and it must not grow that\n+ (decision 28).\n - `notifier.ts` keeps one Discord card per run and pings when a run blocks\n (spec Contract 7). `discord.ts` is the REST client and `discord-card.ts` the\n pure payload builder, where every derived string is escaped, stripped and", "status": "modified"}, {"additions": 19, "deletions": 13, "filename": "README.md", "patch": "@@ -132,22 +132,28 @@ curl -X PUT http://localhost:8080/discord/channels/OWNER/NAME \\\n can see, so the ids need not be copied out of Discord by hand. A repo with no\n binding is never notified, and with no token set the service runs as before.\n \n-Better, let the server configure itself (Contract 8). Set `DISCORD_PUBLIC_KEY`\n-to the application's public key, point the application's **Interactions\n-Endpoint URL** at `https://$CUJO_WEBHOOK_HOST/discord/interactions`, re-invite\n-the bot with the `applications.commands` scope alongside `bot`, then authorize\n-the server for a repo:\n+Better, let each repo and each server sort it out between themselves\n+(Contract 8). Once, for the deploy: set `DISCORD_PUBLIC_KEY` to the\n+application's public key, point its **Interactions Endpoint URL** at\n+`https://$CUJO_WEBHOOK_HOST/discord/interactions`, and invite the bot with the\n+`applications.commands` scope alongside `bot`.\n \n-```bash\n-curl -X PUT http://localhost:8080/discord/authorizations/GUILD_ID/OWNER/NAME \\\n- -H 'Host: cujo.localhost'\n+After that there is nothing to run by hand. The repo names the server it trusts:\n+\n+```yaml\n+# .cujo.yml on the default branch\n+discord_guild: \"222222222222222222\"\n ```\n \n-Anyone in that server with Manage Server can then run `/cujo watch`, picking\n-the channel and ping role from Discord's own dropdowns, `/cujo status` to see\n-where each repo goes, and `/cujo test` to post a sample card and prove the path\n-works. Which repos a server may reach stays an operator's decision; which\n-channel they land in does not.\n+and anyone in that server with Manage Server runs `/cujo watch`, picking the\n+channel and ping role from Discord's own dropdowns. `/cujo status` shows where\n+each repo goes, and `/cujo test` posts a sample card to prove the path works.\n+\n+Both halves are required: merging the declaration is what proves you control\n+the repo, and running the command is what proves the server wants it.\n+`PUT /discord/authorizations/:guildId/:owner/:name` remains as an operator\n+override, for moving a repo between servers or for one whose `.cujo.yml` cannot\n+be changed.\n \n The deploy uses the base `docker-compose.yml` alone — the overlay and `Makefile`\n are for local runs only and never touch how it deploys.", "status": "modified"}, {"additions": 56, "deletions": 0, "filename": "docs/decisions.md", "patch": "@@ -541,3 +541,59 @@ converge rather than drifting into two schemas that happen to match today.\n \n Adding a table is still simpler and still preferred. This is for altering one\n that is already out there.\n+\n+## 31. The repo declares its Discord server; the operator route becomes an override\n+\n+Decision 28 made a Cujo operator vouch that a Discord server may see a repo.\n+That was wrong in two ways at once. The authority was misplaced — a Cujo\n+operator is not necessarily anyone who owns the repo, so the check confirmed\n+the wrong fact — and it did not scale, because every repo needed a human with\n+an Access login to run a request by hand. In practice that meant a `curl`,\n+which is a fair thing to object to.\n+\n+A repo now names its server itself:\n+\n+```yaml\n+# .cujo.yml on the default branch\n+discord_guild: \"222222222222222222\"\n+```\n+\n+The authority becomes repo write access, which is the thing that actually\n+correlates with owning a repo. It is self-serve for any number of repos, it is\n+auditable in git history like every other config change, and it is revoked by a\n+commit rather than by finding whoever holds a Cujo login. `.cujo.yml` was\n+already the repo's policy file, read from a ref the pull request cannot change,\n+so the file and the habit both existed.\n+\n+The handshake stays two-sided, which is what stops abuse in both directions.\n+The repo's declaration alone would let anyone route a repo they do not own; the\n+server's `/cujo watch` alone would let anyone send a repo's reviews into a\n+server they do not belong to. Both are still required.\n+\n+Cujo reads the file trusted-side, through the App, from the default branch.\n+Never the sandbox's copy: the sandbox holds the pull request's code, and code\n+that declares its own authorization is not an authorization. Reading the\n+default branch rather than the pull request's is also what makes the\n+declaration proof of control — it has to be merged.\n+\n+The key is extracted with one strict pattern rather than parsed as YAML. It has\n+one shape, a snowflake at the top level, so anything else does not match and\n+the repo counts as undeclared; a YAML dependency for one scalar is not worth\n+the bundle or the parser's own surface. A wrong declaration is silent and never\n+costs a review: `/cujo watch` prints the exact line to add, and `/cujo status`\n+closes with it.\n+\n+Autocomplete deliberately stopped narrowing to what a server may watch, because\n+that would be one `.cujo.yml` read per installed repo per keystroke against a\n+three-second budget. It offers everything the App is installed on, and the\n+refusal carries the fix.\n+\n+What survives from 28: the operator route, now an override for moving a repo\n+between servers or for a repo whose `.cujo.yml` cannot be changed; Manage\n+Server, still checked twice; and the rule that nothing here approves a review.\n+\n+Rejected: a claim-code flow (`/cujo claim` prints a code, someone pastes it\n+into a GitHub issue), which proves the same thing but is a stateful dance with\n+expiry and replay to get right and leaves no lasting record of the decision.\n+Also rejected, again, Manage Server alone — it still lets any server admin bind\n+any repo Cujo knows about.", "status": "modified"}, {"additions": 66, "deletions": 29, "filename": "docs/spec.md", "patch": "@@ -99,6 +99,7 @@ cross back out of the sandbox.\n - GET /orders/1\n allow_hosts: # egress the repo legitimately needs\n - api.stripe.com\n+ discord_guild: \"2222…\" # which Discord server may watch it (Contract 8)\n ```\n \n Any key can be omitted. Missing keys are inferred from the repo; if the\n@@ -625,32 +626,64 @@ role — in the wrong place, behind a login the people who care about the channe\n may not have. This contract moves that choice into Discord without moving the\n decision that matters.\n \n-**Two tiers** (decision 28). They answer different questions and carry\n-different authority:\n+**Two halves** (decisions 28 and 31). They answer different questions and are\n+proved by different people. Neither alone does anything:\n \n-| Tier | Question | Who decides | Where |\n-|------|----------|-------------|-------|\n-| Authorization | Which repos may this Discord server see at all? | An operator, identified by a Cloudflare Access email | `PUT /discord/authorizations/:guildId/:owner/:name` on the UI host |\n-| Binding | Which channel, and which role gets pinged? | A member with Manage Server | `/cujo` in that server |\n+| Half | Question | Proved by | Where |\n+|------|----------|-----------|-------|\n+| Declaration | Which Discord server may have this repo's reviews? | Whoever can merge to the repo's default branch | `discord_guild` in `.cujo.yml` |\n+| Binding | Which channel, and which role gets pinged? | A member with Manage Server | `/cujo watch` in that server |\n \n-So the reach of a server is always a decision with an email attached to it,\n-recorded in `authorized_by`, and everything inside that reach is self-serve.\n-A binding records who made it too: an email, or `discord:`.\n+Without the repo's half, anyone could point a repo they do not own at their own\n+channel. Without the server's half, anyone could send a repo's reviews into a\n+server they do not belong to. A binding records who made it: an email, or\n+`discord:`.\n+\n+```yaml\n+# .cujo.yml on the default branch\n+discord_guild: \"222222222222222222\"\n+```\n+\n+Cujo reads that file through the GitHub App, from the **default branch**, and\n+never from the sandbox's copy — the sandbox holds the pull request's code, and\n+code that declares its own authorization is not an authorization. Reading the\n+default branch rather than the pull request's is also what makes the\n+declaration proof: it has to be merged.\n+\n+The key is extracted, not parsed as YAML. It has one shape — a Discord\n+snowflake at the top level — so anything else simply does not match and the\n+repo counts as undeclared, which is the silent-but-visible behaviour below.\n+\n+**The operator override.** `PUT /discord/authorizations/:guildId/:owner/:name`\n+on the UI host still allows a pair directly, recorded with the operator's\n+Access email in `authorized_by`. It is for moving a repo between servers, and\n+for a repo whose `.cujo.yml` cannot be changed. It is no longer the way\n+notifications are normally set up.\n+\n+**When a declaration is wrong**, nothing fails: a malformed value, a server the\n+bot is not in, or a missing file all mean \"not declared\". Reviews are\n+unaffected — a config typo must not cost a review. `/cujo watch` says exactly\n+what to add and where, and `/cujo status` closes with the line to paste, since\n+listing every repo that named a server would mean reading each installed\n+repo's `.cujo.yml` on every command.\n \n Revoking an authorization also drops the binding it permitted. Leaving the\n channel bound would keep a server receiving reviews it may no longer see.\n \n **The command.** One `/cujo` with four subcommands, so a server gets one entry\n in the picker. `channel:` and `role:` are Discord's own option types, which\n-render as native pickers; `repo:` is completed from the repos the Cujo App is\n-installed on, narrowed to the ones this server is authorized for, so the list\n-doubles as the answer to \"what can I bind here\".\n+render as native pickers; `repo:` is completed from every repo the Cujo App is\n+installed on. It is deliberately not narrowed to the ones this server may\n+watch: that would mean reading each repo's `.cujo.yml` on every keystroke,\n+against a three-second budget. `watch` does one targeted read for the repo that\n+was picked and says exactly what to add if it has not named this server, which\n+teaches more than a row missing from a dropdown.\n \n | Subcommand | Does |\n |------------|------|\n | `/cujo watch repo channel [role]` | Sends that repo's cards to that channel, pinging that role when a review blocks. |\n | `/cujo unwatch repo` | Stops sending them. |\n-| `/cujo status` | What this server is authorized for, and where each repo currently goes. |\n+| `/cujo status` | Where each repo watched here currently goes, plus anything an operator allowed that is not being sent yet, and the line to add to a repo to allow another. |\n | `/cujo test repo` | Posts a sample card to the bound channel. It exercises the token, the channel permissions and the rendering at once, which nothing else can do without waiting for a real pull request. |\n \n Every reply is ephemeral, so configuring makes no noise in the channel.\n@@ -664,26 +697,30 @@ reply says which one failed:\n the bar — but a server admin can change that default, so the handler checks\n the interaction's own `member.permissions` as well. A permission check that\n lives only on the client is not a permission check.\n-3. The server is authorized for the repo (tier one above). `watch` checks this\n- again immediately before it writes: the Discord round trips in between are\n- awaits, and an operator revoking the server during them must not end with a\n- binding written for a server that may no longer see the repo.\n-4. For `watch`: the channel is in **this** server, is a text or announcement\n- channel, and the bot has View Channel, Send Messages and Embed Links there,\n- resolved through the overwrites exactly as Contract 7's bind route does. The\n- channel option comes from this server's own picker, but a request is a\n- request; nothing stops a crafted one naming a channel somewhere else.\n-5. For `watch` with a role: the role is in this server.\n-6. The repo is one the Cujo App is installed on. A repo it is not can be bound\n+3. The repo is one the Cujo App is installed on. A repo it is not can be bound\n and then never notified, which is the silent failure the rest of these\n checks exist to prevent. Only a list Cujo managed to read can refuse a bind:\n GitHub being unreachable is not a reason to block one. The authorization\n- route applies the same check when the pair is first allowed.\n-7. For `watch` and `unwatch`: no **other** authorized server already holds this\n- repo. One repo notifies one channel (Contract 7), so two servers authorized\n- for the same repo would otherwise be able to redirect or silence each\n- other's reviews. Moving a repo between servers is an operator's job, over\n+ route applies the same check when a pair is allowed by hand. This comes\n+ before the next check on purpose: a repo the App cannot see has no readable\n+ `.cujo.yml` either, and \"it has not named this server\" would send someone to\n+ edit a file Cujo could not have read.\n+4. The repo names this server in `.cujo.yml`, or an operator allowed the pair.\n+ `watch` checks this again immediately before it writes: the Discord round\n+ trips in between are awaits, and a declaration reverted or an allowance\n+ withdrawn during them must not end with a binding for a server that may no\n+ longer see the repo.\n+5. For `watch` and `unwatch`: no **other** server already holds this repo. One\n+ repo notifies one channel (Contract 7), so two servers allowed the same repo\n+ would otherwise be able to redirect or silence each other's reviews. Moving\n+ a repo between servers is an operator's job, over\n `PUT /discord/channels/:owner/:name`.\n+6. For `watch`: the channel is in **this** server, is a text or announcement\n+ channel, and the bot has View Channel, Send Messages and Embed Links there,\n+ resolved through the overwrites exactly as Contract 7's bind route does. The\n+ channel option comes from this server's own picker, but a request is a\n+ request; nothing stops a crafted one naming a channel somewhere else.\n+7. For `watch` with a role: the role is in this server.\n \n **Discord's limits are enforced, not hoped for.** A `status` reply is cut with\n a count rather than sent over the 2000-character message cap, since a deferred", "status": "modified"}], "message": "docs: revise Contract 8's authorization and record decision 31\n\nContract 8 described two tiers where the first was an operator's errand. It now\ndescribes two halves, proved by different people: the repo declares which\nserver may have its reviews, the server says which channel. The gate list is\nreordered to match what the code actually checks, since a list labelled \"in\norder\" that is not in order is worse than no list.\n\nDecision 31 is a new entry rather than an edit to 28, per this file's own rule\nabout reversing rather than deleting. It states what was wrong -- misplaced\nauthority, and no path that scaled past a human running curl -- what survives\nfrom 28, and the two alternatives rejected again.\n\n`.cujo.yml`'s schema in Contract 2 gains the key, since that is where a reader\nlooks for what the file may contain.\n\nClaude-Session: https://claude.ai/code/session_01EUqoBcrZVQSDEYngwih2hv", "sha": "272d8d49f35dd8c6c22e6ce91bb73ac993ccc616"}], "post_review_commits": ["fc825b03ffb1c6123fe79c866b01964ab73a3f7c"], "pr_author": "spencerjireh", "pr_title": "feat(cujo): let a repo name its own Discord server in .cujo.yml", "repo_name": "spencerjireh/cujo"}, "repo": "spencerjireh/cujo", "snapshot": "snapshots/0d8cd33588b7468617c1943d388ac4edb23f4f06c8f5b0660872b34a342b6041.pack", "split": "eval", "task_id": "11f19ec014da9511dfb8c6d5de7c1093f2c2e07eb8fbc5c84b91b5e0163b8005"} {"base_sha": "bee93a3ea1881dc1edee6446f44f1a3afb6ad350", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/Codagent-AI/agent-skills/pull/44", "id": "129837eb3269acaf153e7c3e26540c16d7b7786fa2aacdf77ca18085428b092f", "preparation_mode": "source-only", "snapshot": {"base_ref": "bee93a3ea1881dc1edee6446f44f1a3afb6ad350", "base_sha": "bee93a3ea1881dc1edee6446f44f1a3afb6ad350", "body": "", "head_ref": "8e8e633997b6d63fb45eaab7cd00d66663cc8115", "head_sha": "8e8e633997b6d63fb45eaab7cd00d66663cc8115", "name": "agent-skills", "number": 44, "owner": "Codagent-AI", "pr_url": "https://github.com/Codagent-AI/agent-skills/pull/44", "title": ""}}, "head_sha": "8e8e633997b6d63fb45eaab7cd00d66663cc8115", "metadata": {"group_id": "001ba5eb5f6e044feadfaa6b07082a33a01d755a6dc2911983c0e59b4a884308", "snapshot": {"base_sha": "bee93a3ea1881dc1edee6446f44f1a3afb6ad350", "external_requirements": [], "head_sha": "8e8e633997b6d63fb45eaab7cd00d66663cc8115", "objects": 114, "objects_sha256": "a8b9159b38b6b351d4239c4edbddb13cf10e67965d365fd1b04cb7800d53a51d", "patch_sha256": "6bf6cdad7718366e0bd9cf0f3607193aaa38f16ce4216cd5881d89f049148b52"}}, "pr_number": 44, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "99a3d3c1c706", "description": "Acceptance evidence could be written after CI checked a different PR revision from the one exercised in the flow pass; the tested SHA, CI-reported SHA, and current local and PR heads were not explicitly compared after waiting.", "file_path": "skills/prepare-acceptance/SKILL.md"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "99a3d3c1c706", "description": "The CI poller did not return the PR head SHA, so callers could not verify which revision its check results applied to.", "file_path": "skills/wait-ci/scripts/check-ci.sh"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "99a3d3c1c706", "description": "The acceptance procedure directed product, scope, and design ambiguities into the resolved-assumptions ledger even though they still required a human decision.", "file_path": "skills/prepare-acceptance/SKILL.md"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "0516128e7892", "description": "Top-level bot status and summary comments were treated as blocking PR feedback, causing CI to report `comments` when no actionable review comment existed.", "file_path": "skills/wait-ci/scripts/get-pr-comments.sh"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "0516128e7892", "description": "Unresolved review threads authored by the PR creator were filtered out, potentially hiding feedback that still needed resolution.", "file_path": "skills/wait-ci/scripts/get-pr-comments.sh"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "0516128e7892", "description": "The wait procedure could report completion while a review bot explicitly said its review was still in progress; it did not recheck that status within the overall deadline or report an unfinished review as pending.", "file_path": "skills/wait-ci/SKILL.md"}], "commits_under_review": [{"author": "pacaplan", "date": "2026-07-20T00:27:33Z", "files": [{"additions": 1, "deletions": 1, "filename": "docs/introduction.md", "patch": "@@ -17,7 +17,7 @@ The core skills cover four parts of the development lifecycle:\n \n - Planning: `propose`, `proposal-review`, `spec`, `design`, `plan-tasks`, `review-spec`, and `simple-plan`\n - Implementation: `implement-with-tdd`, `implement-and-validate`, and `implement-change`\n-- Pull requests: `push-pr`, `wait-ci`, `fix-pr`, and `finalize-pr`\n+- Pull requests: `push-pr`, `wait-ci`, `prepare-acceptance`, `fix-pr`, and `finalize-pr`\n - Support and review: `init`, `ask-questions`, `handoff`, `session-report`, `review-assumptions`, and `task-compliance`\n \n The repository also includes a separate release skill under `.agents/skills/release` and `.claude/skills/release`. That release skill is for maintainers of this repository, not part of the installed user-facing Codagent workflow.", "status": "modified"}, {"additions": 4, "deletions": 0, "filename": "docs/skills-reference.md", "patch": "@@ -67,6 +67,10 @@ Commits local changes, pushes the branch, and creates or updates the current bra\n \n Polls CI for the current branch PR. It reports pass, fail, pending, or comments status; fetches failed GitHub Actions logs; checks blocking reviews; and surfaces unresolved PR comments.\n \n+### `prepare-acceptance`\n+\n+Prepares a draft PR for human acceptance. It exercises every supported user or client flow through the real product surface, reports clear defects to the caller, captures screenshots for every UI flow or client-style evidence for non-UI flows, waits for current-head CI once stable, and writes revision-bound acceptance-test and handoff artifacts. Fixes and automated validation are handled by the caller.\n+\n ### `fix-pr`\n \n Fixes CI failures and review comments for the current branch PR. It gathers failure context, dispatches a fixer subagent, verifies the fix with Agent Validator, pushes, and resolves addressed review threads when possible.", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "docs/workflow-guide.md", "patch": "@@ -59,6 +59,8 @@ Tasks are ordered so dependent work stays sequential.\n \n `wait-ci` polls the current branch PR, reports CI status, gathers failed GitHub Actions logs, checks blocking reviews, and surfaces unresolved PR comments.\n \n+`prepare-acceptance` supports workflows that separate autonomous implementation from human acceptance. Starting from a draft PR, it exercises every supported user or client flow through the real product surface, captures screenshots for UI flows or client-style evidence for APIs and CLIs, reports clear defects to the caller, waits for CI on a stable tested head, and produces a concise evidence package for the human review session. Fixes and automated validation remain the caller's responsibility.\n+\n `fix-pr` addresses CI failures and review comments by dispatching a fixer subagent, verifying the fix, and pushing.\n \n `finalize-pr` orchestrates the full loop: push PR, wait for CI, fix failures or comments, and repeat until the PR is green or the documented termination rules require a pause.", "status": "modified"}, {"additions": 184, "deletions": 0, "filename": "skills/prepare-acceptance/SKILL.md", "patch": "@@ -0,0 +1,184 @@\n+---\n+description: >\n+ Exercises an implemented change through its user and client flows, reports clear defects to a\n+ caller-managed fix and validation loop, waits for current-head CI once stable, and prepares concise\n+ evidence for human review. Use when preparing a change for acceptance, gathering review evidence,\n+ performing human-style flow testing, or when invoked as codagent:prepare-acceptance.\n+---\n+\n+# Prepare Acceptance\n+\n+Prepare an implemented change for a separate human acceptance session. Exercise it as a human user or\n+real client would, report clear defects, wait for CI once no defects remain, and produce concise\n+evidence bound to the exact PR revision. Fixes and automated validation belong to separate\n+caller-managed steps.\n+\n+## Required inputs\n+\n+Resolve these from the caller before acting:\n+\n+- approved requirements, scenarios, design, and task artifacts;\n+- caller-supplied implementation summary or completion evidence identifying delivered behavior;\n+- evidence output directory;\n+- unresolved-assumptions ledger path, when one exists;\n+- required PR state.\n+\n+Treat missing source-of-truth artifacts or an unspecified evidence directory as blockers. Do not infer\n+product behavior from implementation alone. Keep this workflow autonomous: preserve product, scope,\n+or design ambiguity for the later human acceptance session instead of asking the user here.\n+\n+## Procedure\n+\n+### 1. Pin the tested revision\n+\n+1. Read repository instructions, the approved artifacts, the unresolved-assumptions ledger, and the\n+ existing automated-validation evidence supplied by the caller.\n+2. Record local `HEAD`. Read only the PR URL, current head SHA, and draft state needed for acceptance.\n+ Do not inspect or reconstruct a diff.\n+3. Require a clean tracked worktree, the required PR state, and local `HEAD` equal to the PR head. If\n+ they do not match, stop for the caller to resolve; do not push or alter PR metadata in this skill.\n+\n+### 2. Exercise the product like a user\n+\n+Derive a concise list of supported user or client flows only from the approved artifacts and the\n+caller-supplied implementation evidence. Do not inspect a diff to discover behavior. Exercise every\n+flow end to end through the same public surface a real user or client would use. A flow is a meaningful\n+journey or operation, not every input permutation.\n+\n+- For a web, mobile, desktop, or terminal UI, navigate and operate it through its real interface.\n+- For an API, call it through its documented HTTP, SDK, or CLI surface as a client would. Record a\n+ sanitized request shape, response status and relevant response excerpt, plus observable side effects.\n+- For a CLI or library, invoke its public commands or API as a consumer would and retain representative\n+ input, output, and resulting state.\n+- For background behavior, trigger it through the normal entry point and inspect the user-visible or\n+ externally observable result.\n+\n+Use typical representative data, configuration, and roles. Do not run automated unit, integration, or\n+end-to-end suites, linters, builds, or other automated validation commands; those belong to the caller.\n+Do not fuzz, try bizarre inputs, attempt to break the product, or build an exhaustive edge-case matrix.\n+Test an error, empty, boundary, or transient state only when it is an approved flow or necessary to\n+complete a normal flow.\n+\n+For each flow, record the action, observed outcome, concise evidence, and any limitation. Verify the\n+resulting state instead of relying on task completion or agent assertions.\n+\n+When a clear implementation defect appears, do not fix it. Write\n+`/acceptance-findings.md` with the tested SHA, affected flow, expected and observed\n+behavior, concise reproduction steps, and evidence paths. Do not wait for CI or write final acceptance\n+evidence in that invocation. Report the findings and end with the exact line\n+`ACCEPTANCE_FIX_NEEDED` so the caller can run its fix and validation loop.\n+\n+Append product, scope, or design ambiguity to the caller's assumptions ledger with the decision needed\n+and likely impact; never silently choose an interpretation or report ambiguity as a clear defect. Every\n+invocation re-exercises all supported flows against the current committed `HEAD`; never reuse results\n+or screenshots from an earlier invocation.\n+\n+### 3. Capture visual evidence\n+\n+For any UI—including web, mobile, desktop, and TUI—store screenshots under\n+`/acceptance-screenshots/` as the flows are exercised. Capture at least one\n+meaningful stable result for every UI flow, and more only when multiple states are needed to understand\n+that flow. Do not capture loading, empty, error, responsive, or before/after states unless they are part\n+of the flow being tested.\n+\n+Record for every screenshot:\n+\n+- flow demonstrated;\n+- expected behavior and what the reviewer should notice;\n+- route or command, representative input, and user role when relevant;\n+- tested head SHA;\n+- concise text equivalent.\n+\n+Screenshots support the observed interaction; they are not proof on their own. For non-visual surfaces,\n+retain the corresponding client request/output evidence instead.\n+\n+### 4. Wait for current-head CI\n+\n+Invoke `codagent:wait-ci` after a complete flow pass finds no clear defects and the final tested head is\n+pushed. Require its report to apply to the exact local and PR head SHA used for the flow pass.\n+\n+- `passed`: continue.\n+- `failed`, `comments`, or `pending`: do not write final acceptance-test or handoff evidence or claim\n+ readiness. Report the blocking checks/comments and stop so the caller can route the change through\n+ the appropriate fix path.\n+- no configured checks: continue only after recording that CI coverage is absent.\n+\n+Treat skipped, neutral, cancelled, stale, and timed-out checks as explicit evidence states, never as\n+proof that associated behavior passed.\n+\n+### 5. Write acceptance-test evidence\n+\n+Write `acceptance-test.md` in the evidence directory only after CI passes or is explicitly absent, the\n+complete flow pass makes no tracked changes, and the caller's latest automated-validation evidence\n+applies to the current pushed head. Include:\n+\n+- exact tested local/PR head SHA;\n+- the supported flows exercised and their outcomes;\n+- clear-defect status and any prior workflow fix evidence supplied by the caller;\n+- existing automated-validation and CI status without rerunning either;\n+- screenshot metadata and text equivalents for every UI flow;\n+- representative API, CLI, library, or background-operation evidence for non-UI flows;\n+- unavailable flows, environment limitations, warnings, and residual risks;\n+- new unresolved assumptions added to the canonical ledger.\n+\n+Prefer concise conclusions with durable log paths over raw log dumps.\n+\n+### 6. Prepare the human handoff\n+\n+Collate existing implementation, acceptance-test, automated-validation, and CI evidence. Do not run new\n+acceptance tests, capture replacement screenshots, or fix issues during collation. If evidence is\n+missing or stale, stop and require the producing phase to run again.\n+\n+Write `acceptance-handoff.md` in the evidence directory with:\n+\n+1. **Decision brief** — unresolved decisions, delivered behavior, overall validation status, known\n+ limitations, and suggested human review path.\n+2. **Revision identity** — repository, draft PR URL, exact tested SHA, generation time, and tracked\n+ worktree status.\n+3. **Flow evidence** — each supported flow, what was done, the observed result, its evidence, and any\n+ limitation.\n+4. **Automated validation and CI** — concise status plus durable logs or links produced by the separate\n+ validation and CI steps.\n+5. **Visual and client evidence** — screenshot metadata/text equivalents, API or CLI evidence, and\n+ practical human review instructions.\n+6. **Residual risk** — unavailable flows, environment limitations, warnings, and relevant omissions.\n+7. **Assumption handoff** — canonical ledger path plus a concise summary of every unresolved item.\n+\n+### 7. Verify readiness\n+\n+Before reporting readiness:\n+\n+1. Require a clean tracked worktree.\n+2. Require local `HEAD`, PR head, `acceptance-test.md`, and `acceptance-handoff.md` to name the same SHA.\n+3. Require CI evidence for that SHA to be passing, or explicitly record that no checks exist.\n+4. Verify every referenced evidence and screenshot path exists and every UI flow has visual evidence.\n+5. Ensure persisted evidence does not expose secrets, credentials, tokens, private data, or unrelated\n+ user content.\n+6. Confirm the PR remains a draft.\n+\n+Report the exact ready-for-acceptance SHA, PR URL, handoff path, unresolved-decision count, CI status,\n+and known limitations. End with the exact line `ACCEPTANCE_READY`. Do not mark the PR ready or perform\n+human acceptance.\n+\n+## Result protocol\n+\n+Write the terminal marker to `/acceptance-status.txt` as its only non-empty line,\n+and return the same marker as the final response line:\n+\n+- `ACCEPTANCE_FIX_NEEDED` — one or more clear implementation defects were documented for the caller's\n+ fix and validation loop. Do not emit final acceptance evidence.\n+- `ACCEPTANCE_READY` — no clear defects were found, current-head CI passed or was explicitly absent,\n+ and revision-bound evidence was verified.\n+- `ACCEPTANCE_BLOCKED: ` — required inputs, testing, PR state, CI, or evidence could not be\n+ completed. Do not emit either success marker.\n+\n+## Out of scope\n+\n+- Do not obtain human acceptance; leave that to the interactive acceptance workflow.\n+- Do not fix implementation defects, modify repository files, commit, push, or alter PR metadata.\n+- Do not run automated test suites, linters, builds, or other automated checks; the caller owns them.\n+- Do not run automated validation; the caller owns validation and reinvocation.\n+- Do not change approved requirements, product scope, or design to make tests pass.\n+- Do not archive the change, mark the PR ready, merge, or release.\n+- Do not perform fuzzing, adversarial testing, or exhaustive edge-case exploration.\n+- Do not treat successful task execution, agent summaries, or screenshots alone as proof of behavior.", "status": "added"}, {"additions": 4, "deletions": 0, "filename": "skills/prepare-acceptance/agents/openai.yaml", "patch": "@@ -0,0 +1,4 @@\n+interface:\n+ display_name: \"Prepare Acceptance\"\n+ short_description: \"Exercise product flows and package review evidence\"\n+ default_prompt: \"Use $prepare-acceptance to exercise the implemented user and client flows, wait for CI, and prepare evidence for human acceptance.\"", "status": "added"}], "message": "feat: add prepare acceptance skill", "sha": "8ceaabd589da02660e2255819a970ef39eef2ec4"}, {"author": "pacaplan", "date": "2026-07-20T02:45:10Z", "files": [{"additions": 1, "deletions": 1, "filename": "docs/skills-reference.md", "patch": "@@ -69,7 +69,7 @@ Polls CI for the current branch PR. It reports pass, fail, pending, or comments\n \n ### `prepare-acceptance`\n \n-Prepares a draft PR for human acceptance. It exercises every supported user or client flow through the real product surface, reports clear defects to the caller, captures screenshots for every UI flow or client-style evidence for non-UI flows, waits for current-head CI once stable, and writes revision-bound acceptance-test and handoff artifacts. Fixes and automated validation are handled by the caller.\n+Prepares an implemented PR revision for human acceptance. It exercises every supported user or client flow through the real product surface, reports clear defects to the caller, captures screenshots for every UI flow or client-style evidence for non-UI flows, waits for current-head CI once stable, and writes revision-bound acceptance-test and handoff artifacts. Fixes and any automated validation are handled by the caller; the skill records their evidence or absence and the current PR state without changing it.\n \n ### `fix-pr`\n ", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "docs/workflow-guide.md", "patch": "@@ -59,7 +59,7 @@ Tasks are ordered so dependent work stays sequential.\n \n `wait-ci` polls the current branch PR, reports CI status, gathers failed GitHub Actions logs, checks blocking reviews, and surfaces unresolved PR comments.\n \n-`prepare-acceptance` supports workflows that separate autonomous implementation from human acceptance. Starting from a draft PR, it exercises every supported user or client flow through the real product surface, captures screenshots for UI flows or client-style evidence for APIs and CLIs, reports clear defects to the caller, waits for CI on a stable tested head, and produces a concise evidence package for the human review session. Fixes and automated validation remain the caller's responsibility.\n+`prepare-acceptance` supports workflows that separate autonomous implementation from human acceptance. Starting from an implemented PR revision, it exercises every supported user or client flow through the real product surface, captures screenshots for UI flows or client-style evidence for APIs and CLIs, reports clear defects to the caller, waits for CI on a stable tested head, and produces a concise evidence package for the human review session. Fixes and any automated validation remain the caller's responsibility; the skill records their evidence or absence and the current PR state without changing it.\n \n `fix-pr` addresses CI failures and review comments by dispatching a fixer subagent, verifying the fix, and pushing.\n ", "status": "modified"}, {"additions": 43, "deletions": 46, "filename": "skills/prepare-acceptance/SKILL.md", "patch": "@@ -1,17 +1,17 @@\n ---\n description: >\n Exercises an implemented change through its user and client flows, reports clear defects to a\n- caller-managed fix and validation loop, waits for current-head CI once stable, and prepares concise\n- evidence for human review. Use when preparing a change for acceptance, gathering review evidence,\n- performing human-style flow testing, or when invoked as codagent:prepare-acceptance.\n+ caller without fixing them, waits for current-head CI once stable, and prepares concise evidence for\n+ human review. Use when preparing a change for acceptance, gathering review evidence, performing\n+ human-style flow testing, or when invoked as codagent:prepare-acceptance.\n ---\n \n # Prepare Acceptance\n \n Prepare an implemented change for a separate human acceptance session. Exercise it as a human user or\n real client would, report clear defects, wait for CI once no defects remain, and produce concise\n evidence bound to the exact PR revision. Fixes and automated validation belong to separate\n-caller-managed steps.\n+caller-managed steps when used.\n \n ## Required inputs\n \n@@ -20,23 +20,24 @@ Resolve these from the caller before acting:\n - approved requirements, scenarios, design, and task artifacts;\n - caller-supplied implementation summary or completion evidence identifying delivered behavior;\n - evidence output directory;\n-- unresolved-assumptions ledger path, when one exists;\n-- required PR state.\n+- unresolved-assumptions ledger path, when one exists.\n \n Treat missing source-of-truth artifacts or an unspecified evidence directory as blockers. Do not infer\n-product behavior from implementation alone. Keep this workflow autonomous: preserve product, scope,\n-or design ambiguity for the later human acceptance session instead of asking the user here.\n+product behavior from implementation alone. When no assumptions-ledger path is supplied, use\n+`/acceptance-assumptions.md` and create it if needed. Keep this preparation\n+autonomous: preserve product, scope, or design ambiguity for the later human acceptance session\n+instead of asking the user here.\n \n ## Procedure\n \n ### 1. Pin the tested revision\n \n 1. Read repository instructions, the approved artifacts, the unresolved-assumptions ledger, and the\n existing automated-validation evidence supplied by the caller.\n-2. Record local `HEAD`. Read only the PR URL, current head SHA, and draft state needed for acceptance.\n- Do not inspect or reconstruct a diff.\n-3. Require a clean tracked worktree, the required PR state, and local `HEAD` equal to the PR head. If\n- they do not match, stop for the caller to resolve; do not push or alter PR metadata in this skill.\n+2. Record local `HEAD`. Read only the PR URL, current head SHA, and current PR state needed for the\n+ evidence record. Do not inspect or reconstruct a diff.\n+3. Require a clean tracked worktree and local `HEAD` equal to the PR head. If they do not match, stop\n+ for the caller to resolve; do not push or alter PR metadata in this skill.\n \n ### 2. Exercise the product like a user\n \n@@ -65,10 +66,10 @@ resulting state instead of relying on task completion or agent assertions.\n When a clear implementation defect appears, do not fix it. Write\n `/acceptance-findings.md` with the tested SHA, affected flow, expected and observed\n behavior, concise reproduction steps, and evidence paths. Do not wait for CI or write final acceptance\n-evidence in that invocation. Report the findings and end with the exact line\n-`ACCEPTANCE_FIX_NEEDED` so the caller can run its fix and validation loop.\n+evidence in that invocation. Report the findings clearly so the caller can run its fix and validation\n+process.\n \n-Append product, scope, or design ambiguity to the caller's assumptions ledger with the decision needed\n+Append product, scope, or design ambiguity to the resolved assumptions ledger with the decision needed\n and likely impact; never silently choose an interpretation or report ambiguity as a clear defect. Every\n invocation re-exercises all supported flows against the current committed `HEAD`; never reuse results\n or screenshots from an earlier invocation.\n@@ -98,9 +99,14 @@ Invoke `codagent:wait-ci` after a complete flow pass finds no clear defects and\n pushed. Require its report to apply to the exact local and PR head SHA used for the flow pass.\n \n - `passed`: continue.\n-- `failed`, `comments`, or `pending`: do not write final acceptance-test or handoff evidence or claim\n- readiness. Report the blocking checks/comments and stop so the caller can route the change through\n- the appropriate fix path.\n+- `failed` or `comments`: do not write final acceptance-test or handoff evidence or claim readiness.\n+ When the failure or comment is clearly attributable to the implementation and actionable in the\n+ repository, add it to `/acceptance-findings.md` with the tested SHA, failing\n+ check or comment, relevant log or link, and concise expected-versus-observed behavior. Report it as\n+ a clear defect so the caller can run its fix and validation process. Otherwise, report the external,\n+ environmental, or infrastructure blocker without classifying it as an implementation defect.\n+- `pending`: do not claim readiness. Report the pending checks and stop for the caller to resume or\n+ retry later.\n - no configured checks: continue only after recording that CI coverage is absent.\n \n Treat skipped, neutral, cancelled, stale, and timed-out checks as explicit evidence states, never as\n@@ -109,13 +115,15 @@ proof that associated behavior passed.\n ### 5. Write acceptance-test evidence\n \n Write `acceptance-test.md` in the evidence directory only after CI passes or is explicitly absent, the\n-complete flow pass makes no tracked changes, and the caller's latest automated-validation evidence\n-applies to the current pushed head. Include:\n+complete flow pass makes no tracked changes, and any automated-validation evidence supplied by the\n+caller applies to the current pushed head. Do not require automated-validation evidence when none was\n+supplied; explicitly record its absence instead. Include:\n \n - exact tested local/PR head SHA;\n - the supported flows exercised and their outcomes;\n-- clear-defect status and any prior workflow fix evidence supplied by the caller;\n-- existing automated-validation and CI status without rerunning either;\n+- clear-defect status and any prior fix evidence supplied by the caller;\n+- existing automated-validation and CI status without rerunning either, explicitly noting when\n+ automated-validation evidence was not supplied;\n - screenshot metadata and text equivalents for every UI flow;\n - representative API, CLI, library, or background-operation evidence for non-UI flows;\n - unavailable flows, environment limitations, warnings, and residual risks;\n@@ -125,20 +133,21 @@ Prefer concise conclusions with durable log paths over raw log dumps.\n \n ### 6. Prepare the human handoff\n \n-Collate existing implementation, acceptance-test, automated-validation, and CI evidence. Do not run new\n-acceptance tests, capture replacement screenshots, or fix issues during collation. If evidence is\n-missing or stale, stop and require the producing phase to run again.\n+Collate existing implementation, acceptance-test, available automated-validation, and CI evidence. Do\n+not run new acceptance tests, capture replacement screenshots, or fix issues during collation. If\n+required evidence is missing or stale, stop and require the producing phase to run again. The explicit\n+absence of caller-supplied automated-validation evidence is not missing evidence.\n \n Write `acceptance-handoff.md` in the evidence directory with:\n \n 1. **Decision brief** — unresolved decisions, delivered behavior, overall validation status, known\n limitations, and suggested human review path.\n-2. **Revision identity** — repository, draft PR URL, exact tested SHA, generation time, and tracked\n+2. **Revision identity** — repository, PR URL, exact tested SHA, generation time, and tracked\n worktree status.\n 3. **Flow evidence** — each supported flow, what was done, the observed result, its evidence, and any\n limitation.\n-4. **Automated validation and CI** — concise status plus durable logs or links produced by the separate\n- validation and CI steps.\n+4. **Automated validation and CI** — concise status plus durable logs or links produced by separate\n+ validation and CI steps; explicitly say when automated-validation evidence was not supplied.\n 5. **Visual and client evidence** — screenshot metadata/text equivalents, API or CLI evidence, and\n practical human review instructions.\n 6. **Residual risk** — unavailable flows, environment limitations, warnings, and relevant omissions.\n@@ -154,30 +163,18 @@ Before reporting readiness:\n 4. Verify every referenced evidence and screenshot path exists and every UI flow has visual evidence.\n 5. Ensure persisted evidence does not expose secrets, credentials, tokens, private data, or unrelated\n user content.\n-6. Confirm the PR remains a draft.\n+6. Record the current PR state for the caller without changing it.\n \n Report the exact ready-for-acceptance SHA, PR URL, handoff path, unresolved-decision count, CI status,\n-and known limitations. End with the exact line `ACCEPTANCE_READY`. Do not mark the PR ready or perform\n-human acceptance.\n-\n-## Result protocol\n-\n-Write the terminal marker to `/acceptance-status.txt` as its only non-empty line,\n-and return the same marker as the final response line:\n-\n-- `ACCEPTANCE_FIX_NEEDED` — one or more clear implementation defects were documented for the caller's\n- fix and validation loop. Do not emit final acceptance evidence.\n-- `ACCEPTANCE_READY` — no clear defects were found, current-head CI passed or was explicitly absent,\n- and revision-bound evidence was verified.\n-- `ACCEPTANCE_BLOCKED: ` — required inputs, testing, PR state, CI, or evidence could not be\n- completed. Do not emit either success marker.\n+and known limitations. Do not mark the PR ready or perform human acceptance. The caller owns any\n+machine-readable status file, terminal marker, or control-flow protocol.\n \n ## Out of scope\n \n-- Do not obtain human acceptance; leave that to the interactive acceptance workflow.\n+- Do not obtain human acceptance; leave that to the later human acceptance session.\n - Do not fix implementation defects, modify repository files, commit, push, or alter PR metadata.\n-- Do not run automated test suites, linters, builds, or other automated checks; the caller owns them.\n-- Do not run automated validation; the caller owns validation and reinvocation.\n+- Do not run automated test suites, linters, builds, other automated checks, or automated validation;\n+ the caller owns validation and reinvocation.\n - Do not change approved requirements, product scope, or design to make tests pass.\n - Do not archive the change, mark the PR ready, merge, or release.\n - Do not perform fuzzing, adversarial testing, or exhaustive edge-case exploration.", "status": "modified"}], "message": "refactor: decouple acceptance result protocol", "sha": "ff1994a134fd1d214799c22f288a52df0b95eb50"}, {"author": "pacaplan", "date": "2026-07-20T02:47:05Z", "files": [], "message": "Merge branch 'main' of https://github.com/Codagent-AI/agent-skills into fix/plan-task-sizing", "sha": "5b56fd48bef8b2bc0005f9e38c379e24176eb5ab"}, {"author": "pacaplan", "date": "2026-07-20T02:47:39Z", "files": [{"additions": 1, "deletions": 1, "filename": ".claude-plugin/marketplace.json", "patch": "@@ -9,7 +9,7 @@\n \"plugins\": [\n {\n \"name\": \"codagent\",\n- \"version\": \"0.7.6\",\n+ \"version\": \"0.8.0\",\n \"source\": \"./\",\n \"description\": \"A curated set of skills for each stage of development — propose, spec, design, plan, implement, ship.\",\n \"license\": \"MIT\",", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": ".claude-plugin/plugin.json", "patch": "@@ -1,6 +1,6 @@\n {\n \"name\": \"codagent\",\n- \"version\": \"0.7.6\",\n+ \"version\": \"0.8.0\",\n \"description\": \"A curated set of skills for each stage of development — propose, spec, design, plan, implement, ship.\",\n \"license\": \"MIT\"\n }", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": ".codex-plugin/plugin.json", "patch": "@@ -1,6 +1,6 @@\n {\n \"name\": \"codagent\",\n- \"version\": \"0.7.6\",\n+ \"version\": \"0.8.0\",\n \"description\": \"A curated set of skills for each stage of development - propose, spec, design, plan, implement, ship.\",\n \"author\": {\n \"name\": \"Codagent-AI\",", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": ".cursor-plugin/plugin.json", "patch": "@@ -1,7 +1,7 @@\n {\n \"name\": \"codagent\",\n \"displayName\": \"Codagent Agent Skills\",\n- \"version\": \"0.7.6\",\n+ \"version\": \"0.8.0\",\n \"description\": \"A curated set of skills for each stage of development — propose, spec, design, plan, implement, ship.\",\n \"author\": \"Codagent-AI\",\n \"license\": \"MIT\",", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "CHANGELOG.md", "patch": "@@ -1,5 +1,11 @@\n # agent-skills\n \n+## 0.8.0\n+\n+### Minor Changes\n+\n+- [#44](https://github.com/Codagent-AI/agent-skills/pull/44) Add reusable human-style acceptance testing, revision-bound review evidence, and caller-owned correction and control-flow integration.\n+\n ## 0.7.6\n \n ### Patch Changes", "status": "modified"}], "message": "chore: release v0.8.0", "sha": "8e8e633997b6d63fb45eaab7cd00d66663cc8115"}], "post_review_commits": ["99a3d3c1c706bb74a0ce59822e115b29aeaf2d7d", "0516128e7892fc6aa8b4115394e5e44bb8d3e7b2"], "pr_author": "pacaplan", "pr_title": "feat: add prepare acceptance skill", "repo_name": "Codagent-AI/agent-skills"}, "repo": "Codagent-AI/agent-skills", "snapshot": "snapshots/001ba5eb5f6e044feadfaa6b07082a33a01d755a6dc2911983c0e59b4a884308.pack", "split": "eval", "task_id": "129837eb3269acaf153e7c3e26540c16d7b7786fa2aacdf77ca18085428b092f"} {"base_sha": "2dcd44365a23558f9fa4baab6112d2a43cb84c03", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/kimchanhyung98/openusage/pull/55", "id": "1402d94dd499c801251df8410827f11eca1913b52c907435804bdf021c16c695", "preparation_mode": "source-only", "snapshot": {"base_ref": "2dcd44365a23558f9fa4baab6112d2a43cb84c03", "base_sha": "2dcd44365a23558f9fa4baab6112d2a43cb84c03", "body": "", "head_ref": "df3f901eed33d0807b350aa15a3894e821839616", "head_sha": "df3f901eed33d0807b350aa15a3894e821839616", "name": "openusage", "number": 55, "owner": "kimchanhyung98", "pr_url": "https://github.com/kimchanhyung98/openusage/pull/55", "title": ""}}, "head_sha": "df3f901eed33d0807b350aa15a3894e821839616", "metadata": {"group_id": "132968bed5d77e80f6e2db10024f28c1c107520aff33b25a55550e901c66d2df", "snapshot": {"base_sha": "2dcd44365a23558f9fa4baab6112d2a43cb84c03", "external_requirements": [], "head_sha": "df3f901eed33d0807b350aa15a3894e821839616", "objects": 939, "objects_sha256": "0b211503d94edf61e17665f3702c05ec99df53ca618b0f533fc4b0ce30dc0060", "patch_sha256": "3f29441fc309cf0b0895643444118575c468d57f6ac6a969016aa53998d569cb"}}, "pr_number": 55, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "f869668009be", "description": "Malformed lines containing a \"usage\" candidate, or candidates whose JSON root was not an object, were silently skipped before the scanner marked the file as rejected, so no decoding diagnostic was emitted.", "file_path": "Sources/OpenUsage/Providers/Claude/ClaudeLogUsageScanner.swift"}, {"action_id": "A2", "action_type": "fix", "category": "documentation", "commit_sha": "f869668009be", "description": "The diagnostics documentation implied that every usage entry excluded for missing model pricing emitted a history_scan/other event, although entries without a model name or positive token count do not.", "file_path": "docs/research/claude-local-usage-diagnostics.md"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "fe0bba99df34", "description": "The diagnostics documentation overstated which usage-format failures emit decoding events: valid JSON with a missing or non-object message.usage is skipped without a diagnostic.", "file_path": "docs/research/claude-local-usage-diagnostics.md"}, {"action_id": "A4", "action_type": "improvement", "category": "documentation", "commit_sha": "31f1ccfe0e5b", "description": "The diagnostics documentation did not explicitly cover top-level JSON object conversion failures or distinguish them from valid objects whose message.usage is absent or not an object.", "file_path": "docs/research/claude-local-usage-diagnostics.md"}], "commits_under_review": [{"author": "kimchanhyung98", "date": "2026-09-17T05:31:21Z", "files": [{"additions": 6, "deletions": 1, "filename": "docs/providers/claude.md", "patch": "@@ -142,7 +142,12 @@ Claude가 활성화돼 있으면 실행 시, 활성화 시, 5분마다, 대시\n - **\"Updates blocked by Anthropic\"**(Claude 헤더의 황색 경고) — 사용량 API가 OpenUsage를 제한하는 상태.\n 같은 로그인의 마지막 값을 유지하고 재시도 시각을 표시하며 그동안 재시도 간격을 늘림.\n 다른 로그인은 새 캐시와 쿨다운으로 시작.\n-- **지출 타일에 \"No data\" 표시** — 지난 30일간 Claude Code 로그를 찾지 못한 상태.\n+- **지출 타일에 \"No data\" 표시** — 해당 기간에 합산 가능한 로컬 기록이 없는 상태.\n+ 기록 부재·파싱 제외·가격 미확정으로 발생 가능하며, 한도 API와 별도 데이터 출처이므로 Session·Weekly 정상 표시와 공존 가능.\n+ JSONL의 `usage` 키와 콜론·객체 사이 공백·탭 허용; 이전 캐시도 버전 변경 후 재파싱.\n+ 형식 제외는 `history_scan/decoding`, 모델 가격 미확정은 `history_scan/other`로 기존 로그·동의 기반 익명 진단에 기록.\n+ 형식 제외는 파일 재파싱 시에만 기록하므로 캐시 hit의 이벤트 부재를 정상 스캔 증거로 해석하지 않음.\n+ 제보 근거와 검증 범위는 [로컬 사용량 누락 검토](/docs/research/claude-local-usage-diagnostics.md) 참조.\n 관리형 계정 전환 외의 경우 로그가 커스텀 위치에 있으면 `CLAUDE_CONFIG_DIR`을 설정해 Claude Code와 OpenUsage가 같은 위치 사용.\n 관리형 터미널 전환은 공유 `~/.claude` 홈 사용.\n 다른 커스텀 홈에 둔 로그인은 Settings에 등록하기 전까지 아예 표시하지 않음.", "status": "modified"}, {"additions": 39, "deletions": 0, "filename": "docs/research/claude-local-usage-diagnostics.md", "patch": "@@ -0,0 +1,39 @@\n+# Claude 로컬 사용량 누락 검토\n+\n+## 증거와 한계\n+\n+제보 화면은 Session·Weekly·Fable 값이 있으나 Today·Yesterday 비용·토큰은 `No data`, 일부 과거 Trend 존재.\n+제보자의 앱 버전·실제 사용 환경·원본 로그 미확인.\n+현재 Mac의 Claude 데이터로 제보를 재현하지 않음.\n+\n+2026-09-17의 PostHog 조회에서 0.12.0 Claude 일일 집계는 성공 898회·실패 7회, 실패 범주는 network.\n+같은 설치의 여러 프로바이더가 같은 시각에 실패한 기록도 있으나 제보자와 연결할 근거 없음.\n+이 수치는 당시 수신 이벤트의 집계이며 전체 사용자 장애율이나 제보 해결의 증거 아님.\n+\n+## 최소 수정\n+\n+- 확인된 코드 문제: 파일 파서가 정확한 `\"usage\":{` 문자열만 찾아 동등한 공백 포함 JSONL을 제외.\n+- 후보는 `\"usage\"` 키로 좁히고 디코딩된 `message.usage`로 최종 검증.\n+- 금지 null은 디코딩된 필드로 검사해 공백 우회와 문자열 본문 오인 방지.\n+- Claude 캐시 버전 `3 → 4`; 이전에 빈 배열로 저장된 파일도 재파싱.\n+- 중복 제거·Advisor 합산·가격 미확정 기록 제외 정책 유지.\n+\n+## 로그와 PostHog\n+\n+기존 `AppDiagnostics` → `TelemetryRecorder` → `TelemetryPrivacy` 경로 사용.\n+파일 파싱에서 확인된 형식 제외는 `history_scan`, `degraded`, `decoding`으로 기록.\n+모델 가격 부재로 합계에서 제외한 기록은 `history_scan`, `degraded`, `other`로 기록.\n+각각 파일 재파싱 또는 집계 호출당 한 번 기록하며, 숫자 손상은 기존 진단 유지.\n+원격으로 원문·모델명·경로·토큰·비용을 추가 전송하지 않으며 기존 동의·중복 억제·일일 상한 유지.\n+정상 미사용 이벤트나 기간별 이벤트, 새 원격 필드, 별도 파일 메타데이터 캐시 추가 없음.\n+\n+배포 후 해당 버전의 `feature_operation_result`·`feature_operation_daily`에서 `operation=history_scan`, `provider_id=claude`와 오류 범주 확인.\n+즉시 이벤트와 일일 `count`는 중복 계산 금지.\n+파싱 제외는 파일 재파싱 시에만 진단하므로 캐시 사용 시 기록이 없을 수 있음.\n+정상 부재와 읽기·파싱·가격 문제는 여전히 제보 시각의 지원 자료와 함께 판단 필요.\n+\n+## 검증 경계\n+\n+합성 JSONL의 공백·null·Advisor·부분 집계와 기존 진단 이벤트에 대한 회귀 테스트 유지.\n+현재 Mac의 실제 Claude 파일·인증·앱 실행은 검증에 사용하지 않음.\n+Xcode 라이선스 미동의로 Swift 빌드·테스트 실행 전 중단; 컴파일 및 회귀 테스트 통과 미확인.", "status": "added"}], "message": "docs(claude): explain local usage gaps and diagnostic limits", "sha": "bbfb1d331f3daff68b345765de8b45439b69e67e"}, {"author": "kimchanhyung98", "date": "2026-09-17T05:31:21Z", "files": [{"additions": 37, "deletions": 27, "filename": "Sources/OpenUsage/Providers/Claude/ClaudeLogUsageScanner.swift", "patch": "@@ -36,8 +36,8 @@ actor ClaudeLogUsageScanner {\n \n /// 같은 Claude home을 읽는 카드들의 공유 actor — 첫 스캔이 캐시를 채우고 나머지는 재사용.\n /// 테스트는 격리된 메모리 전용 scanner 주입.\n- /// 숫자 검증 이전 형식의 parse cache 재사용 방지 — `Entry` 의미 변경 시 bump.\n- static let cacheSchemaVersion = 3\n+ /// 공백이 있는 usage를 제외하던 이전 parse cache의 재사용 방지.\n+ static let cacheSchemaVersion = 4\n \n private static let sharedScanner = IncrementalJSONLScanner(\n logTag: LogTag.plugin(\"claude\"),\n@@ -229,12 +229,21 @@ actor ClaudeLogUsageScanner {\n \n /// 세션 파일 1개의 모든 usage 라인 파싱 — 날짜 window는 집계 시 적용, window 이동에도 캐시된 파싱 유효.\n static func parseFile(_ data: Data) -> [Entry] {\n- let marker = Data(#\"\"usage\":{\"#.utf8)\n+ let marker = Data(#\"\"usage\"\"#.utf8)\n var entries: [Entry] = []\n+ var rejected = false\n for line in data.split(separator: UInt8(ascii: \"\\n\")) {\n- guard line.range(of: marker) != nil else { continue }\n- if hasUnsupportedNullField(line) { continue }\n- entries.append(contentsOf: parseEntries(Data(line)))\n+ guard line.range(of: marker) != nil,\n+ let object = (try? JSONSerialization.jsonObject(with: Data(line))) as? [String: Any],\n+ let message = object[\"message\"] as? [String: Any],\n+ message[\"usage\"] is [String: Any] else { continue }\n+ let parsed = hasUnsupportedNullValue(object) ? [] : parseEntries(object)\n+ if parsed.isEmpty { rejected = true }\n+ entries.append(contentsOf: parsed)\n+ }\n+ if rejected {\n+ AppDiagnostics.record(.historyScan, result: .degraded, category: .decoding, providerID: \"claude\",\n+ localContext: \"Claude usage records were skipped because their format is unsupported\")\n }\n UsageLogNumbers.reportRejectedRows(entries.filter(\\.invalidNumericValues).count, source: \"claude\")\n return entries\n@@ -248,8 +257,12 @@ actor ClaudeLogUsageScanner {\n /// top-level usage는 main-model entry 유지, `usage.iterations`의 advisor-message만 별도 entry —\n /// ccusage와 동일, 일반 iteration 재집계 금지.\n private static func parseEntries(_ data: Data) -> [Entry] {\n- guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],\n- let timestampRaw = object[\"timestamp\"] as? String,\n+ guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return [] }\n+ return parseEntries(object)\n+ }\n+\n+ private static func parseEntries(_ object: [String: Any]) -> [Entry] {\n+ guard let timestampRaw = object[\"timestamp\"] as? String,\n let timestamp = OpenUsageISO8601.date(from: timestampRaw),\n let message = object[\"message\"] as? [String: Any],\n let usage = message[\"usage\"] as? [String: Any],\n@@ -362,28 +375,19 @@ actor ClaudeLogUsageScanner {\n return index < bytes.count && bytes[index].isASCIIDigit\n }\n \n- /// Claude가 `null`을 쓰지 않는 필드에 null이 있으면 외부/손상 로그 — ccusage와 byte 단위 동일 기준으로 skip.\n+ /// 디코딩된 필드로 null 검사 — 공백 우회와 문자열 본문의 가짜 키 오인 방지.\n static func hasUnsupportedNullField(_ line: Data.SubSequence) -> Bool {\n- let nullMarker = Data(\":null\".utf8)\n- let quote = UInt8(ascii: \"\\\"\")\n- let bytes = Data(line) // 새 복사본 — 인덱스 0 기준\n- var offset = bytes.startIndex\n- while let markerRange = bytes.range(of: nullMarker, in: offset.. 0 ? start - 1 : 0\n- if bytes[fieldEnd] != quote {\n- while fieldEnd > 0, bytes[fieldEnd] != quote { fieldEnd -= 1 }\n- }\n- if bytes[fieldEnd] == quote, fieldEnd > 0 {\n- var fieldStart = fieldEnd - 1\n- while fieldStart > 0, bytes[fieldStart] != quote { fieldStart -= 1 }\n- if bytes[fieldStart] == quote {\n- let field = String(decoding: bytes[(fieldStart + 1).. Bool {\n+ if let object = value as? [String: Any] {\n+ return object.contains { key, value in\n+ (unsupportedNullableFields.contains(key) && value is NSNull) || hasUnsupportedNullValue(value)\n }\n- offset = markerRange.upperBound\n }\n+ if let array = value as? [Any] { return array.contains(where: hasUnsupportedNullValue) }\n return false\n }\n \n@@ -459,6 +463,7 @@ actor ClaudeLogUsageScanner {\n static func aggregate(entries: [Entry], since: Date, pricing: ModelPricing) -> LogUsageScan {\n var accumulator = DailyUsageAccumulator()\n var rejectedNumericRows = 0\n+ var pricingUnavailable = false\n \n for entry in entries where entry.timestamp >= since {\n guard !entry.invalidNumericValues else {\n@@ -478,13 +483,18 @@ actor ClaudeLogUsageScanner {\n } else {\n if let model = trimmedModel, entry.tokens.totalTokens > 0 {\n accumulator.addUnknownModel(day: day, model: model)\n+ pricingUnavailable = true\n }\n continue\n }\n \n accumulator.add(day: day, tokens: entry.tokens.totalTokens, cost: cost, model: modelName)\n }\n \n+ if pricingUnavailable {\n+ AppDiagnostics.record(.historyScan, result: .degraded, category: .other, providerID: \"claude\",\n+ localContext: \"Claude usage records were excluded because model pricing is unavailable\")\n+ }\n return accumulator.build(rejectedNumericRows: rejectedNumericRows, source: \"claude\")\n }\n }", "status": "modified"}], "message": "fix(claude): accept whitespace in usage logs and report exclusions\n\nValidation: static diff checks passed. Focused SwiftPM tests could not start because the Xcode license has not been accepted. No live app or account data was used.", "sha": "f64422abff5c9c20d4d3832c4117fe314027a541"}, {"author": "kimchanhyung98", "date": "2026-09-17T05:31:21Z", "files": [{"additions": 99, "deletions": 0, "filename": "Tests/OpenUsageTests/ClaudeLogParsingTests.swift", "patch": "@@ -0,0 +1,99 @@\n+import XCTest\n+@testable import OpenUsage\n+\n+final class ClaudeLogParsingTests: XCTestCase {\n+ private var directory: URL!\n+ private var previousSink: LogFile!\n+\n+ override func setUpWithError() throws {\n+ directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)\n+ previousSink = AppLog.sink\n+ AppLog.sink = LogFile(directory: directory, fileName: \"fixture.log\")\n+ }\n+\n+ override func tearDownWithError() throws {\n+ AppLog.sink = previousSink\n+ try? FileManager.default.removeItem(at: directory)\n+ }\n+\n+ func testWhitespacePreservesFileParsingAndDeduplication() {\n+ let line = ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", input: 17, output: 9, costUSD: 0.25)\n+ let compact = ClaudeLogUsageScanner.parseFile(Data(line.utf8))\n+ XCTAssertEqual(compact.count, 1)\n+ for separator in [\": \", \" : \", \"\\t:\\t\"] {\n+ let spaced = line.replacingOccurrences(of: \"\\\":\", with: \"\\\"\" + separator)\n+ let parsed = ClaudeLogUsageScanner.parseFile(Data(spaced.utf8))\n+ XCTAssertEqual(parsed, compact)\n+ XCTAssertEqual(ClaudeLogUsageScanner.dedup(compact + parsed), compact)\n+ }\n+ }\n+\n+ func testNullChecksRejectWhitespaceVariantsWithoutRejectingQuotedContent() throws {\n+ let line = ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", input: 1, output: 2)\n+ var object = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any])\n+ object[\"note\"] = #\"example: \"speed\":null, \"usage\":{}\"#\n+ XCTAssertEqual(ClaudeLogUsageScanner.parseFile(try JSONSerialization.data(withJSONObject: object)).count, 1)\n+ object[\"costUSD\"] = NSNull()\n+ let null = String(decoding: try JSONSerialization.data(withJSONObject: object), as: UTF8.self)\n+ for separator in [\":\", \": \", \"\\t:\\t\"] {\n+ let spaced = null.replacingOccurrences(of: \"\\\":\", with: \"\\\"\" + separator)\n+ XCTAssertTrue(ClaudeLogUsageScanner.parseFile(Data(spaced.utf8)).isEmpty)\n+ }\n+ }\n+\n+ func testAdvisorTotalsSurviveWhitespaceAndUnsupportedRowsReportOncePerFile() throws {\n+ let capture = ClaudeParsingDiagnosticCapture()\n+ let observer = AppDiagnostics.observe { event, _ in capture.append(event) }\n+ defer { AppDiagnostics.removeObserver(observer) }\n+ let valid = #\"{\"timestamp\":\"2026-09-17T03:00:00Z\",\"costUSD\":0.25,\"message\":{\"id\":\"parent\",\"model\":\"fixture-parent\",\"usage\" : {\"input_tokens\":10,\"output_tokens\":5,\"iterations\":[{\"type\":\"advisor_message\",\"model\":\"fixture-advisor\",\"input_tokens\":3,\"output_tokens\":2}]}}}\"#\n+ let invalid = ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", input: 1, output: 2, speed: \"unknown\")\n+ let lines = [valid, invalid, invalid, #\"{\"message\":{\"content\":\"usage\"}}\"#].joined(separator: \"\\n\")\n+ let entries = ClaudeLogUsageScanner.parseFile(Data(lines.utf8))\n+ XCTAssertEqual(entries.count, 2)\n+ XCTAssertEqual(entries.first?.costUSD, 0.25)\n+ XCTAssertEqual(entries.last?.tokens.totalTokens, 5)\n+ XCTAssertEqual(entries.last?.messageID, \"parent:advisor:0\")\n+ XCTAssertEqual(capture.events, [DiagnosticEvent(.historyScan, result: .degraded, category: .decoding, providerID: \"claude\")])\n+ }\n+\n+ func testUnpricedUsagePreservesKnownTotalsAndEmitsOnlyFixedDiagnostic() throws {\n+ let capture = ClaudeParsingDiagnosticCapture()\n+ let observer = AppDiagnostics.observe { event, _ in capture.append(event) }\n+ defer { AppDiagnostics.removeObserver(observer) }\n+ let lines = [\n+ ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", input: 10, output: 5, costUSD: 0.25),\n+ ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", model: \"PRIVATE_MODEL\", input: 100, output: 20, messageID: \"unknown\"),\n+ ]\n+ let entries = ClaudeLogUsageScanner.parseFile(Data(lines.joined(separator: \"\\n\").utf8))\n+ let scan = ClaudeLogUsageScanner.aggregate(entries: entries, since: .distantPast, pricing: .empty)\n+ XCTAssertEqual(scan.series.daily.first?.totalTokens, 15)\n+ XCTAssertEqual(scan.series.daily.first?.costUSD, 0.25)\n+ XCTAssertEqual(capture.events, [DiagnosticEvent(.historyScan, result: .degraded, category: .other, providerID: \"claude\")])\n+ XCTAssertFalse(String(decoding: try JSONEncoder().encode(capture.events), as: UTF8.self).contains(\"PRIVATE_MODEL\"))\n+ }\n+\n+ func testNewCacheVersionReparsesAnUnchangedPreviouslySkippedFile() async throws {\n+ let line = ClaudeLogFixture.usageLine(timestamp: \"2026-09-17T03:00:00Z\", input: 10, output: 5, costUSD: 0.25)\n+ .replacingOccurrences(of: \"\\\":\", with: \"\\\" : \")\n+ let home = try ClaudeLogFixture.makeHome(files: [\"project/usage.jsonl\": line])\n+ defer { try? FileManager.default.removeItem(at: home) }\n+ let files = JSONLScanning.jsonlFiles(under: home.appendingPathComponent(\"projects\"))\n+ var persistence = JSONLScanCachePersistence(namespace: \"claude\", schemaVersion: 3,\n+ directory: home.appendingPathComponent(\"cache\"), writeDebounce: .milliseconds(1))\n+ let old = IncrementalJSONLScanner(persistence: persistence)\n+ _ = await old.items(from: files, since: .distantPast, cacheIdentity: \"fixture\", parse: { _ in [] })\n+ await old.flushPendingWrites()\n+ persistence.schemaVersion = ClaudeLogUsageScanner.cacheSchemaVersion\n+ let updated = IncrementalJSONLScanner(persistence: persistence)\n+ let entries = await updated.items(from: files, since: .distantPast, cacheIdentity: \"fixture\", parse: ClaudeLogUsageScanner.parseFile)\n+ XCTAssertEqual(entries?.first?.tokens.totalTokens, 15)\n+ await updated.flushPendingWrites()\n+ }\n+}\n+\n+private final class ClaudeParsingDiagnosticCapture: @unchecked Sendable {\n+ private let lock = NSLock()\n+ private var values: [DiagnosticEvent] = []\n+ var events: [DiagnosticEvent] { lock.withLock { values } }\n+ func append(_ event: DiagnosticEvent) { lock.withLock { values.append(event) } }\n+}", "status": "added"}], "message": "test(claude): cover log formatting pricing and cache migration\n\nValidation: static diff checks passed. Focused SwiftPM tests could not start because the Xcode license has not been accepted. No live app or account data was used.", "sha": "df3f901eed33d0807b350aa15a3894e821839616"}], "post_review_commits": ["f869668009be4ad196b31e4404f4765c171e252c", "fe0bba99df3403efe0e8155b35709ada757e6dcc", "31f1ccfe0e5b51bdf57b01c85d5495513e51970c"], "pr_author": "kimchanhyung98", "pr_title": "fix(claude): prevent usage logs with JSON whitespace from being skipped", "repo_name": "kimchanhyung98/openusage"}, "repo": "kimchanhyung98/openusage", "snapshot": "snapshots/132968bed5d77e80f6e2db10024f28c1c107520aff33b25a55550e901c66d2df.pack", "split": "eval", "task_id": "1402d94dd499c801251df8410827f11eca1913b52c907435804bdf021c16c695"} {"base_sha": "ccc3ebc70a82ff30e145624aac1eb5c961ac09a4", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/badass-courses/ai-hero/pull/127", "id": "147a968cb933af29ed18e6ab9d7a83a28fe99671cc7357a7b787c8d9f178241e", "preparation_mode": "source-only", "snapshot": {"base_ref": "ccc3ebc70a82ff30e145624aac1eb5c961ac09a4", "base_sha": "ccc3ebc70a82ff30e145624aac1eb5c961ac09a4", "body": "", "head_ref": "6822ccdba78f44249ec3551d0aedbfbdbe2aa0a3", "head_sha": "6822ccdba78f44249ec3551d0aedbfbdbe2aa0a3", "name": "ai-hero", "number": 127, "owner": "badass-courses", "pr_url": "https://github.com/badass-courses/ai-hero/pull/127", "title": ""}}, "head_sha": "6822ccdba78f44249ec3551d0aedbfbdbe2aa0a3", "metadata": {"group_id": "0381d29b888654b36380eeadfb9125bd749ce281d494ce2b6a7e5f3b8340be92", "snapshot": {"base_sha": "ccc3ebc70a82ff30e145624aac1eb5c961ac09a4", "external_requirements": [], "head_sha": "6822ccdba78f44249ec3551d0aedbfbdbe2aa0a3", "objects": 2232, "objects_sha256": "2060bd13c1eeb3d65ec001c781db0e2b24a0c821cc04f49bd5618e9a6319aaa5", "patch_sha256": "ba68c1721d8c39b7df8cc2a0d617c41114c056587ae6d8978fdfff6d2eb62ae2"}}, "pr_number": 127, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "aa1bb8c8294e", "description": "An uncaught rejection from getCachedCohort caused the entire MDX server render to fail, taking down the lesson or landing page instead of isolating the office-hours schedule embed.", "file_path": "apps/ai-hero/src/utils/compile-mdx.tsx"}], "commits_under_review": [{"author": "vojtaholik", "date": "2026-08-19T14:33:21Z", "files": [{"additions": 3, "deletions": 88, "filename": "apps/ai-hero/src/components/office-hours-schedule.tsx", "patch": "@@ -18,20 +18,13 @@ import { cn } from '@coursebuilder/utils/cn'\n \n type OfficeHoursScheduleProps = {\n \tsessions?: CohortOfficeHoursSession[]\n-\tcohortId?: string\n \tvariant?: 'lesson' | 'cohort'\n \tshowActions?: boolean | 'false' | 'true'\n \ttimeZone?: string\n \ttimeZoneLabel?: string\n \tclassName?: string\n }\n \n-type CohortOfficeHoursResource = {\n-\tfields?: {\n-\t\tofficeHoursSessions?: CohortOfficeHoursSession[]\n-\t}\n-}\n-\n function formatLocalDate(date: string, timeZone: string | null) {\n \tif (!timeZone) {\n \t\treturn formatOfficeHoursUtcDate(date)\n@@ -131,90 +124,14 @@ function downloadOfficeHoursIcs(sessions: CohortOfficeHoursSession[]) {\n \tURL.revokeObjectURL(url)\n }\n \n-function useOfficeHoursSessions(props: OfficeHoursScheduleProps): {\n-\tsessions: CohortOfficeHoursSession[]\n-\tisLoading: boolean\n-} {\n-\tconst [fetchedSessions, setFetchedSessions] = React.useState<\n-\t\tCohortOfficeHoursSession[]\n-\t>(props.sessions || [])\n-\tconst [isLoading, setIsLoading] = React.useState(\n-\t\t!props.sessions && Boolean(props.cohortId),\n-\t)\n-\n-\tReact.useEffect(() => {\n-\t\tif (props.sessions) {\n-\t\t\tsetFetchedSessions(props.sessions)\n-\t\t\tsetIsLoading(false)\n-\t\t}\n-\t}, [props.sessions])\n-\n-\tReact.useEffect(() => {\n-\t\tif (props.sessions || !props.cohortId) return\n-\n-\t\tconst cohortId = props.cohortId\n-\t\tlet isCancelled = false\n-\n-\t\tconst loadSessions = async () => {\n-\t\t\tsetIsLoading(true)\n-\n-\t\t\ttry {\n-\t\t\t\tconst response = await fetch(\n-\t\t\t\t\t`/api/resources?slugOrId=${encodeURIComponent(cohortId)}&type=cohort`,\n-\t\t\t\t)\n-\t\t\t\tif (!response.ok) {\n-\t\t\t\t\tthrow new Error(\n-\t\t\t\t\t\t`Failed to load cohort office hours: ${response.status}`,\n-\t\t\t\t\t)\n-\t\t\t\t}\n-\n-\t\t\t\tconst resource = (await response.json()) as CohortOfficeHoursResource\n-\t\t\t\tif (!isCancelled) {\n-\t\t\t\t\tsetFetchedSessions(resource.fields?.officeHoursSessions || [])\n-\t\t\t\t}\n-\t\t\t} catch (error) {\n-\t\t\t\tif (!isCancelled) {\n-\t\t\t\t\tconsole.error(error)\n-\t\t\t\t\tsetFetchedSessions([])\n-\t\t\t\t}\n-\t\t\t} finally {\n-\t\t\t\tif (!isCancelled) {\n-\t\t\t\t\tsetIsLoading(false)\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\n-\t\tvoid loadSessions()\n-\n-\t\treturn () => {\n-\t\t\tisCancelled = true\n-\t\t}\n-\t}, [props.cohortId, props.sessions])\n-\n-\treturn {\n-\t\tsessions: fetchedSessions,\n-\t\tisLoading,\n-\t}\n-}\n-\n export function OfficeHoursSchedule({\n-\tsessions: initialSessions,\n-\tcohortId,\n+\tsessions = [],\n \tvariant = 'lesson',\n \tshowActions = true,\n \ttimeZone: configuredTimeZone,\n \ttimeZoneLabel,\n \tclassName,\n }: OfficeHoursScheduleProps) {\n-\tconst { sessions, isLoading } = useOfficeHoursSessions({\n-\t\tsessions: initialSessions,\n-\t\tcohortId,\n-\t\tvariant,\n-\t\tshowActions,\n-\t\ttimeZone: configuredTimeZone,\n-\t\ttimeZoneLabel,\n-\t\tclassName,\n-\t})\n \tconst [detectedTimeZone, setDetectedTimeZone] = React.useState(\n \t\tconfiguredTimeZone || null,\n \t)\n@@ -247,17 +164,15 @@ export function OfficeHoursSchedule({\n \tconst timeRangeLabel = timeZoneLabel || undefined\n \tconst isDetectingTimeZone = !configuredTimeZone && !detectedTimeZone\n \n-\tif (isLoading || isDetectingTimeZone) {\n+\tif (isDetectingTimeZone) {\n \t\treturn (\n \t\t\t\n-\t\t\t\t{isLoading\n-\t\t\t\t\t? 'Loading office hours schedule…'\n-\t\t\t\t\t: 'Detecting your timezone…'}\n+\t\t\t\tDetecting your timezone…\n \t\t\t\n \t\t)\n \t}", "status": "modified"}, {"additions": 31, "deletions": 19, "filename": "apps/ai-hero/src/utils/compile-mdx.tsx", "patch": "@@ -24,6 +24,7 @@ import { PromoCard } from '@/components/mdx/promo-card'\n import type { PromoCardProps } from '@/components/mdx/promo-card'\n import type { DictionaryEntry } from '@/lib/ai-coding-dictionary'\n import { createCalloutLineAutoInsertRemarkPlugin } from '@/lib/callout-line-autoinsert'\n+import { getCachedCohort } from '@/lib/cohorts-query'\n import { createDictionaryAutoLinkRemarkPlugin } from '@/lib/dictionary-autolink'\n import { log } from '@/server/logger'\n import { measureIfSlow } from '@/server/perf'\n@@ -123,6 +124,32 @@ const DynamicOfficeHoursSchedule = dynamic(() =>\n \t\t(mod) => mod.OfficeHoursSchedule,\n \t),\n )\n+\n+type OfficeHoursScheduleMdxProps = React.ComponentProps<\n+\ttypeof DynamicOfficeHoursSchedule\n+> & {\n+\tcohortId?: string\n+}\n+\n+// Sessions resolve here on the server: a browser fetch of the cohort\n+// resource hits the auth-gated /api/resources as an anonymous request and\n+// 401s, silently hiding the schedule — which is exactly what happened to\n+// past cohorts' office-hours pages after the API gained its auth gate.\n+// Async server components are valid MDX components under RSC rendering,\n+// but the MDX types don't know that, hence the cast at the registration.\n+async function OfficeHoursScheduleWithSessions({\n+\tsessions,\n+\tcohortId,\n+\t...props\n+}: OfficeHoursScheduleMdxProps) {\n+\tconst resolvedSessions =\n+\t\tsessions ??\n+\t\t(cohortId\n+\t\t\t? ((await getCachedCohort(cohortId))?.fields?.officeHoursSessions ?? [])\n+\t\t\t: [])\n+\n+\treturn \n+}\n const Quiz = dynamic(() =>\n \timport('@/components/mdx/quiz').then((mod) => mod.Quiz),\n )\n@@ -622,25 +649,10 @@ async function compileMDXInternal(\n \t\t\t\t\tQuizQuestion: (props) => (\n \t\t\t\t\t\t\n \t\t\t\t\t),\n-\t\t\t\t\tOfficeHoursSchedule: ({\n-\t\t\t\t\t\tsessions,\n-\t\t\t\t\t\tcohortId,\n-\t\t\t\t\t\tvariant,\n-\t\t\t\t\t\tshowActions,\n-\t\t\t\t\t\ttimeZone,\n-\t\t\t\t\t\ttimeZoneLabel,\n-\t\t\t\t\t\tclassName,\n-\t\t\t\t\t}) => (\n-\t\t\t\t\t\t\n-\t\t\t\t\t),\n+\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- async\n+\t\t\t\t\t// server components are valid MDX components under RSC rendering,\n+\t\t\t\t\t// but @types/mdx cannot express them.\n+\t\t\t\t\tOfficeHoursSchedule: OfficeHoursScheduleWithSessions as any,\n \t\t\t\t\t...components,\n \t\t\t\t},\n \t\t\t\toptions: {", "status": "modified"}], "message": "fix(office-hours): resolve schedule sessions on the server, not via 401ing fetch\n\nThe OfficeHoursSchedule MDX embed fetched its cohort's sessions from the\nbrowser via /api/resources. Since that route gained its auth gate\n(91b3095), every such fetch — browsers never send an Authorization\nheader — got a 401, the component swallowed it and rendered nothing.\nThat hid the office-hours replay links on both past cohorts' Office\nHours lessons and the schedule on the public cohort landing page.\n\nThe MDX mapping is server-side already, so it now resolves sessions\nthrough getCachedCohort and hands them to the client component, which\nloses its fetch machinery entirely.\n\nCo-Authored-By: Claude Fable 5 ", "sha": "6822ccdba78f44249ec3551d0aedbfbdbe2aa0a3"}], "post_review_commits": ["aa1bb8c8294ec0d3b50d71057b30ee7482b6d1e9"], "pr_author": "vojtaholik", "pr_title": "fix(office-hours): resolve schedule sessions on the server, not via 401ing fetch", "repo_name": "badass-courses/ai-hero"}, "repo": "badass-courses/ai-hero", "snapshot": "snapshots/0381d29b888654b36380eeadfb9125bd749ce281d494ce2b6a7e5f3b8340be92.pack", "split": "eval", "task_id": "147a968cb933af29ed18e6ab9d7a83a28fe99671cc7357a7b787c8d9f178241e"} {"base_sha": "1e58f4144f75a908919ef342259a255b31fad361", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/wave-av/sdk/pull/106", "id": "1b07ec5d6c503f31dbe8a631fd73e1552e99f6effaaadcb2e8a4e7fb79bce9c4", "preparation_mode": "source-only", "snapshot": {"base_ref": "1e58f4144f75a908919ef342259a255b31fad361", "base_sha": "1e58f4144f75a908919ef342259a255b31fad361", "body": "", "head_ref": "ee31ad5a70cae68e451860742439a271468c36ce", "head_sha": "ee31ad5a70cae68e451860742439a271468c36ce", "name": "sdk", "number": 106, "owner": "wave-av", "pr_url": "https://github.com/wave-av/sdk/pull/106", "title": ""}}, "head_sha": "ee31ad5a70cae68e451860742439a271468c36ce", "metadata": {"group_id": "0bc3abdb1259314a7a2213bce738dd66b0ca34633ae3669c4b49e30c0b6efe83", "snapshot": {"base_sha": "1e58f4144f75a908919ef342259a255b31fad361", "external_requirements": [], "head_sha": "ee31ad5a70cae68e451860742439a271468c36ce", "objects": 436, "objects_sha256": "0adef7ff66a645f1ea68aa4279f2d46fb0ff2c9622b877784fc2af1daf711a40", "patch_sha256": "3f9ee69d91041743b9c1f3cbba3454cf1c4dda0afc1b6f17a374e913c9d0b12c"}}, "pr_number": 106, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "7cc9a4a6e821", "description": "The testing contract used the obsolete `testmd` command in its instructions instead of the `contracts` CLI used to validate and run it.", "file_path": "TESTING.md"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "7cc9a4a6e821", "description": "The `npm test` suite was not marked required, so the receipt gate could pass without requiring the project's test suite to succeed.", "file_path": "TESTING.md"}, {"action_id": "A3", "action_type": "fix", "category": "documentation", "commit_sha": "7cc9a4a6e821", "description": "The testing instructions implied that `.testmd/receipts/` would be added to `.gitignore`, although the contract did not make that change. The revised text makes receipt tracking an explicit repository decision; it does not prevent accidental commits of receipts.", "file_path": "TESTING.md"}, {"action_id": "A4", "action_type": "fix", "category": "security", "commit_sha": "f079ab797f90", "description": "The permissions contract had no approval rule for `doppler *`, leaving this repository's secret-manager operations without the intended ask requirement.", "file_path": "PERMISSIONS.md"}, {"action_id": "A5", "action_type": "fix", "category": "security", "commit_sha": "f079ab797f90", "description": "The permissions contract omitted the `secret-write` crossing, so writing a secret to a vault was not explicitly designated as requiring approval.", "file_path": "PERMISSIONS.md"}], "commits_under_review": [{"author": "wave-contract-rollout", "date": "2026-08-30T01:09:21Z", "files": [{"additions": 55, "deletions": 0, "filename": "PERMISSIONS.md", "patch": "@@ -0,0 +1,55 @@\n+# PERMISSIONS\n+\n+What an agent may do in this repository without asking, what it must ask\n+before, and what it may never do. The fenced `yaml permissions-contract` block\n+below is the machine surface: `contracts eval` renders a verdict for one\n+tool call, the PreToolUse gate refuses or asks citing the rule, and\n+`permd compile` turns it into a Claude Code settings fragment. Semantics are\n+deny > ask > allow — when several rules match, the most restrictive wins.\n+Edit the YAML, keep the fence line exactly as-is. Never soften a rule to get\n+past a gate: the gate is the contract.\n+\n+```yaml permissions-contract\n+version: \"0.1\"\n+rules:\n+ - verdict: deny\n+ tool: Bash\n+ cmd_pattern: \"rm -rf *\"\n+ reason: destructive shell\n+ - verdict: deny\n+ tool: Bash\n+ cmd_pattern: \"git push --force*\"\n+ reason: rewriting shared history is operator-owned\n+ - verdict: ask\n+ tool: Bash\n+ cmd_pattern: \"git push*\"\n+ reason: remote mutation\n+ - verdict: deny\n+ path_glob: \"**/*.pem\"\n+ reason: key material stays unread\n+ - verdict: allow\n+ tool: Bash\n+ cmd_pattern: \"npm test*\"\n+ - verdict: allow\n+ tool: Read\n+floors:\n+ merge:\n+ default: pr-review\n+ prod: ask\n+ deploy:\n+ default: staged\n+ prod: ask\n+crossings:\n+ - name: prod-merge\n+ verdict: ask\n+ - name: credential-mint\n+ verdict: deny\n+ reason: operator-owned, never autonomous\n+```\n+\n+## Notes for contributors\n+\n+- `cmd_pattern` and `path_glob` use `*` and `?` only (a linear matcher, never a\n+ regex) — a pattern is matched against the whole command string.\n+- Add rules; do not delete `deny` rules to unblock an agent. If a deny is\n+ wrong, change it in a reviewed PR with the reason in the commit.", "status": "added"}, {"additions": 43, "deletions": 0, "filename": "TESTING.md", "patch": "@@ -0,0 +1,43 @@\n+# TESTING\n+\n+How to run this project's tests, for people and for agents. The fenced\n+`yaml test-contract` block below is the machine surface: `testmd validate`\n+checks it, `testmd run` executes it and writes receipts, and the stop gate\n+verifies receipts before an agent may claim DONE. Edit the YAML, keep the\n+fence line exactly as-is, and never paste secret values into it (fixture\n+NAMES only).\n+\n+```yaml test-contract\n+version: \"0.1\"\n+entry: npm test\n+suites:\n+ unit:\n+ cmd: npm test\n+ timeout_s: 600\n+ lint:\n+ cmd: npm run lint\n+ required: false\n+ timeout_s: 120\n+pass:\n+ exit: 0\n+forbidden:\n+ - skip-failing\n+ - delete-tests\n+ - mock-prod\n+ - claim-pass-on-timeout\n+flake:\n+ retries: 0\n+ on_flaky: fail\n+receipt:\n+ format: json\n+ path: .testmd/receipts\n+ bind: gitCommit\n+```\n+\n+## Notes for contributors\n+\n+- `testmd run` executes every suite and writes one receipt per suite under\n+ `.testmd/receipts/` (add that directory to `.gitignore`).\n+- A receipt is bound to the contract text AND the git commit it ran at; edit\n+ either and the receipt goes stale — re-run.\n+- Optional suites (`required: false`) may fail without failing the gate.", "status": "added"}], "message": "chore(contracts): add TESTING.md + PERMISSIONS.md — contract-files E5-FLEET batch A2 (observe mode, one reversible commit)", "sha": "ee31ad5a70cae68e451860742439a271468c36ce"}], "post_review_commits": ["7cc9a4a6e821c230f1552629b232c6d2d64edb56", "f079ab797f9057c5eb12051c0e557c5772ee7843"], "pr_author": "yakimoto", "pr_title": "chore(contracts): add TESTING.md + PERMISSIONS.md", "repo_name": "wave-av/sdk"}, "repo": "wave-av/sdk", "snapshot": "snapshots/0bc3abdb1259314a7a2213bce738dd66b0ca34633ae3669c4b49e30c0b6efe83.pack", "split": "eval", "task_id": "1b07ec5d6c503f31dbe8a631fd73e1552e99f6effaaadcb2e8a4e7fb79bce9c4"} {"base_sha": "6b74ad0f3f728a39912e4464ac1789c460737e09", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/AprilNEA/OpenLogi/pull/140", "id": "1e4eb4af611d562b47b153250ee13ae615f28ec5c6c9bdd308879d05370e9d85", "preparation_mode": "source-only", "snapshot": {"base_ref": "6b74ad0f3f728a39912e4464ac1789c460737e09", "base_sha": "6b74ad0f3f728a39912e4464ac1789c460737e09", "body": "", "head_ref": "902e79306844214475b6b0108fec65a80d23d9fa", "head_sha": "902e79306844214475b6b0108fec65a80d23d9fa", "name": "OpenLogi", "number": 140, "owner": "AprilNEA", "pr_url": "https://github.com/AprilNEA/OpenLogi/pull/140", "title": ""}}, "head_sha": "902e79306844214475b6b0108fec65a80d23d9fa", "metadata": {"group_id": "03f88f5ba1474507194c482a08b9dca7f8fe7e8093dccf79dab2772b3127e3d8", "snapshot": {"base_sha": "6b74ad0f3f728a39912e4464ac1789c460737e09", "external_requirements": [], "head_sha": "902e79306844214475b6b0108fec65a80d23d9fa", "objects": 238, "objects_sha256": "590b9f5f92cebcc605769badbc06909014ff03b411fb5f25160ea0bd57489ac5", "patch_sha256": "906723f4eef7611ddfdf010d101da46af048ad68332cbe14c59f75d5ee98f0dd"}}, "pr_number": 140, "references": {"actions": [{"action_id": "A1", "action_type": "cleanup", "category": "performance", "commit_sha": "d3d0bda1fe7e", "description": "The backon dependency enabled default async sleep backends for Tokio and gloo-timers even though asset syncing uses only blocking sleep, adding unnecessary dependency edges.", "file_path": "Cargo.toml"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "bc0825cf572d", "description": "A failed asset sync was retried on every inventory tick, repeatedly contacting a permanently unreachable host every few seconds. Retries needed a capped, increasing delay without permanently giving up on recovery.", "file_path": "crates/openlogi-gui/src/main.rs"}], "commits_under_review": [{"author": "AprilNEA", "date": "2026-06-05T10:27:39Z", "files": [{"additions": 12, "deletions": 0, "filename": "Cargo.lock", "patch": "@@ -555,6 +555,17 @@ dependencies = [\n \"arrayvec\",\n ]\n \n+[[package]]\n+name = \"backon\"\n+version = \"1.6.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef\"\n+dependencies = [\n+ \"fastrand 2.4.1\",\n+ \"gloo-timers\",\n+ \"tokio\",\n+]\n+\n [[package]]\n name = \"backtrace\"\n version = \"0.3.76\"\n@@ -4544,6 +4555,7 @@ name = \"openlogi-assets\"\n version = \"0.5.0\"\n dependencies = [\n \"anyhow\",\n+ \"backon\",\n \"serde\",\n \"serde_json\",\n \"sha2\",", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "Cargo.toml", "patch": "@@ -51,6 +51,7 @@ serde_json = \"1\"\n toml = \"0.8\"\n ureq = { version = \"3\", default-features = false, features = [\"rustls\", \"json\"] }\n sha2 = \"0.10\"\n+backon = \"1.6\"\n clap = { version = \"4\", features = [\"derive\", \"env\"] }\n anyhow = \"1\"\n thiserror = \"2\"", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "crates/openlogi-assets/Cargo.toml", "patch": "@@ -17,6 +17,7 @@ ureq = { workspace = true }\n sha2 = { workspace = true }\n anyhow = { workspace = true }\n tracing = { workspace = true }\n+backon = { workspace = true }\n \n [lints]\n workspace = true", "status": "modified"}, {"additions": 81, "deletions": 10, "filename": "crates/openlogi-assets/src/http.rs", "patch": "@@ -15,9 +15,10 @@ use std::path::Path;\n use std::time::Duration;\n \n use anyhow::{Context as _, Result};\n+use backon::{BlockingRetryable, ExponentialBuilder};\n use serde::de::DeserializeOwned;\n use sha2::{Digest, Sha256};\n-use tracing::debug;\n+use tracing::{debug, warn};\n use ureq::Agent;\n \n use crate::index::{FileEntry, Index};\n@@ -35,6 +36,14 @@ const INDEX_NAME: &str = \"index.json\";\n /// time, so a slow-but-progressing download of a large asset isn't killed.\n const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);\n \n+/// Retries after the initial attempt for a single GET (3 tries total).\n+const MAX_RETRIES: usize = 2;\n+\n+/// Backoff before the first retry; doubles each attempt (200ms, 400ms,\n+/// plus jitter). Keeps a transient blip from needing an app restart\n+/// without a fleet of clients hammering the host in lockstep.\n+const RETRY_MIN_DELAY: Duration = Duration::from_millis(200);\n+\n /// Blocking client for one asset host.\n ///\n /// Holds a reused [`ureq::Agent`], so the dozens-to-hundreds of small file\n@@ -127,18 +136,54 @@ impl AssetClient {\n Ok(FetchOutcome::Fetched { bytes })\n }\n \n- /// GET `url` on the shared agent and read the whole body into memory.\n- /// `read_to_vec` caps the body at ureq's default 10 MB — ample for the\n- /// registry JSON and the device PNGs, and a safety net against a\n+ /// GET `url` on the shared agent and read the whole body into memory,\n+ /// retrying transient failures (timeouts, dropped connections, 5xx) with\n+ /// exponential backoff. Permanent failures (4xx, malformed request) fail\n+ /// fast. `read_to_vec` caps the body at ureq's default 10 MB — ample for\n+ /// the registry JSON and the device PNGs, and a safety net against a\n /// runaway response.\n+ ///\n+ /// The backoff sleeps block the calling thread, which is fine: every\n+ /// caller runs on the sync's dedicated background thread, never the\n+ /// async runtime. `backon` defaults to `std::thread::sleep` here.\n fn get_bytes(&self, url: &str) -> Result> {\n- self.agent\n- .get(url)\n+ let policy = ExponentialBuilder::default()\n+ .with_min_delay(RETRY_MIN_DELAY)\n+ .with_factor(2.0)\n+ .with_max_times(MAX_RETRIES)\n+ .with_jitter();\n+ (|| self.try_get_bytes(url))\n+ .retry(policy)\n+ .when(is_retryable)\n+ .notify(|e: &ureq::Error, dur: Duration| {\n+ warn!(%url, backoff_ms = dur.as_millis(), error = ?e, \"transient fetch error — retrying\");\n+ })\n .call()\n- .with_context(|| format!(\"GET {url}\"))?\n- .body_mut()\n- .read_to_vec()\n- .with_context(|| format!(\"read body {url}\"))\n+ .map_err(|e| anyhow::Error::new(e).context(format!(\"GET {url}\")))\n+ }\n+\n+ /// One GET + full body read, surfacing the typed [`ureq::Error`] so the\n+ /// retry loop in [`get_bytes`](Self::get_bytes) can tell transient\n+ /// failures from permanent ones.\n+ fn try_get_bytes(&self, url: &str) -> std::result::Result, ureq::Error> {\n+ self.agent.get(url).call()?.body_mut().read_to_vec()\n+ }\n+}\n+\n+/// Whether a failed fetch is worth retrying. Transport-level hiccups\n+/// (timeouts, dropped/refused connections, DNS blips) and 5xx — plus the two\n+/// \"back off and retry\" 4xx codes — are transient; a 4xx like 404 or a\n+/// malformed-request error won't change on a retry.\n+fn is_retryable(error: &ureq::Error) -> bool {\n+ use ureq::Error;\n+ match error {\n+ Error::StatusCode(code) => *code >= 500 || matches!(*code, 408 | 429),\n+ Error::Io(_)\n+ | Error::Timeout(_)\n+ | Error::ConnectionFailed\n+ | Error::HostNotFound\n+ | Error::Protocol(_) => true,\n+ _ => false,\n }\n }\n \n@@ -175,3 +220,29 @@ pub fn sha256_of_file(path: &Path) -> Result {\n pub fn cached_matches(path: &Path, expected_sha: &str) -> bool {\n sha256_of_file(path).is_ok_and(|actual| actual.eq_ignore_ascii_case(expected_sha))\n }\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::is_retryable;\n+ use ureq::Error;\n+\n+ #[test]\n+ fn retries_transient_failures_not_permanent_ones() {\n+ // Transient: server errors, the two \"back off\" 4xx codes, and\n+ // transport-level failures all warrant a retry.\n+ assert!(is_retryable(&Error::StatusCode(500)));\n+ assert!(is_retryable(&Error::StatusCode(503)));\n+ assert!(is_retryable(&Error::StatusCode(408)));\n+ assert!(is_retryable(&Error::StatusCode(429)));\n+ assert!(is_retryable(&Error::HostNotFound));\n+ assert!(is_retryable(&Error::ConnectionFailed));\n+ assert!(is_retryable(&Error::Io(\n+ std::io::ErrorKind::ConnectionReset.into()\n+ )));\n+\n+ // Permanent: a missing file or bad request won't change on retry.\n+ assert!(!is_retryable(&Error::StatusCode(404)));\n+ assert!(!is_retryable(&Error::StatusCode(400)));\n+ assert!(!is_retryable(&Error::StatusCode(403)));\n+ }\n+}", "status": "modified"}], "message": "feat(assets): retry transient asset fetches with exponential backoff\n\nA single failed GET (DNS blip, dropped connection, 5xx) used to abort the\nwhole sync; combined with the GUI latching the sync after one attempt, a\ndevice could sit on the synthetic silhouette until the app was restarted.\n\nWrap the blocking GET + body read in backon's exponential backoff (3\ntries, 200ms base, jittered). is_retryable classifies the typed ureq\nerror so transport hiccups and 5xx (plus 408/429) retry while a 404 or\nmalformed request fails fast. The sleeps block, which is fine — every\ncaller runs on the sync's dedicated background thread.", "sha": "46de8d0c80d542a4e6952748c8c27cb94cf49ff0"}, {"author": "AprilNEA", "date": "2026-06-05T10:27:58Z", "files": [{"additions": 8, "deletions": 7, "filename": "crates/openlogi-gui/src/asset/sync.rs", "patch": "@@ -51,13 +51,14 @@ pub fn sync(server: &str, models: &[(DeviceModelInfo, Option)]) -> Resul\n .with_context(|| format!(\"create cache root {}\", cache_root.display()))?;\n \n let client = http::AssetClient::new(server);\n- let index = match client.fetch_index_to_dir(&cache_root) {\n- Ok(idx) => idx,\n- Err(e) => {\n- warn!(error = ?e, \"index.json fetch failed — proceeding with cached files\");\n- return Ok(());\n- }\n- };\n+ // The index is the critical shared resource — if it can't be fetched\n+ // (after the HTTP layer's own retries) bail with an error so the caller\n+ // retries the whole sync on a later device snapshot, rather than latching\n+ // success off a run that downloaded nothing. Per-depot failures below stay\n+ // best-effort: an optional colour variant 404 shouldn't block everything.\n+ let index = client\n+ .fetch_index_to_dir(&cache_root)\n+ .context(\"fetch asset index\")?;\n \n // Each target carries the HID++ `extended_model_id` byte so the\n // depot sync can fetch the right colour variant. `OPENLOGI_FORCE_DEPOT`", "status": "modified"}, {"additions": 52, "deletions": 17, "filename": "crates/openlogi-gui/src/main.rs", "patch": "@@ -43,6 +43,7 @@ mod windows;\n // gpui-component ships, so the framework's own widgets localize alongside ours.\n rust_i18n::i18n!(\"locales\", fallback = \"en\");\n \n+use std::sync::atomic::{AtomicU8, Ordering};\n use std::sync::{Arc, RwLock};\n \n use anyhow::Result;\n@@ -237,20 +238,37 @@ fn main() -> Result<()> {\n });\n \n let mut hook_handle = None;\n- // Asset depots are fetched once, in the background, when devices\n- // first appear — startup no longer blocks on it.\n- let mut assets_synced = false;\n+ // Asset depots are fetched in the background when devices first\n+ // appear — startup no longer blocks on it. The sync runs once on\n+ // success, but a failed attempt is retried on the next snapshot\n+ // instead of being latched off for the session (see SYNC_*).\n+ let sync_state = Arc::new(AtomicU8::new(SYNC_IDLE));\n loop {\n tokio::select! {\n Some(new_inv) = inventory_rx.recv() => {\n- // Latch on the first snapshot that actually carries\n- // model info — gating on `!is_empty()` alone could fire\n- // on a device whose DeviceInformation read hasn't\n- // resolved yet, leaving its art un-synced all session.\n- if !assets_synced && !collect_models(&new_inv).is_empty() {\n- assets_synced = true;\n+ // Kick off (or retry) the one-shot asset sync. Gate on a\n+ // snapshot that actually carries model info — `!is_empty()`\n+ // alone could fire on a device whose DeviceInformation read\n+ // hasn't resolved yet, leaving its art un-synced. `RUNNING`\n+ // blocks a second concurrent sync; `DONE` latches it off;\n+ // `FAILED` lets this 2 s tick retry, so a transient network\n+ // error no longer strands the device on the silhouette\n+ // until an app restart.\n+ let state = sync_state.load(Ordering::Acquire);\n+ if matches!(state, SYNC_IDLE | SYNC_FAILED)\n+ && !collect_models(&new_inv).is_empty()\n+ {\n+ sync_state.store(SYNC_RUNNING, Ordering::Release);\n let inv = new_inv.clone();\n- std::thread::spawn(move || sync_assets_if_needed(&inv));\n+ let state = Arc::clone(&sync_state);\n+ std::thread::spawn(move || {\n+ let next = if sync_assets_if_needed(&inv) {\n+ SYNC_DONE\n+ } else {\n+ SYNC_FAILED\n+ };\n+ state.store(next, Ordering::Release);\n+ });\n }\n cx.update(|cx| {\n let cache = asset::AssetResolver::new();\n@@ -330,14 +348,31 @@ fn reconcile_early_config() {\n }\n }\n \n-fn sync_assets_if_needed(inventories: &[DeviceInventory]) {\n+/// Asset-sync state, stored in an [`AtomicU8`] and polled on each inventory\n+/// snapshot. A failed run flips back to [`SYNC_FAILED`] so the next tick\n+/// retries, rather than latching the sync off for the whole session.\n+const SYNC_IDLE: u8 = 0;\n+const SYNC_RUNNING: u8 = 1;\n+const SYNC_DONE: u8 = 2;\n+const SYNC_FAILED: u8 = 3;\n+\n+/// Refresh the asset cache for the connected devices. Returns `true` when the\n+/// sync completed (or wasn't needed) and `false` when it failed and should be\n+/// retried. Runs on a dedicated background thread — the HTTP layer's blocking\n+/// retries are fine here.\n+fn sync_assets_if_needed(inventories: &[DeviceInventory]) -> bool {\n let probe_cache = asset::AssetResolver::new();\n- if asset::sync::should_run(probe_cache.has_bundle_root()) {\n- let server = std::env::var(\"OPENLOGI_ASSETS\")\n- .unwrap_or_else(|_| asset::sync::DEFAULT_BASE.to_string());\n- let models = collect_models(inventories);\n- if let Err(e) = asset::sync::sync(&server, &models) {\n- warn!(error = ?e, \"asset sync raised — continuing with whatever's cached\");\n+ if !asset::sync::should_run(probe_cache.has_bundle_root()) {\n+ return true;\n+ }\n+ let server =\n+ std::env::var(\"OPENLOGI_ASSETS\").unwrap_or_else(|_| asset::sync::DEFAULT_BASE.to_string());\n+ let models = collect_models(inventories);\n+ match asset::sync::sync(&server, &models) {\n+ Ok(()) => true,\n+ Err(e) => {\n+ warn!(error = ?e, \"asset sync failed — will retry on the next device snapshot\");\n+ false\n }\n }\n }", "status": "modified"}], "message": "fix(gui): retry asset sync on failure instead of latching it off\n\nThe startup sync latched a boolean the moment its background thread was\nspawned, so any failure — a swallowed index fetch error, a thread that\nnever downloaded anything — stranded the device on the synthetic\nsilhouette for the rest of the session; only a restart recovered it.\n\nReplace the spawn-time latch with a small atomic state machine polled on\nthe existing 2 s inventory tick: IDLE/FAILED spawns (or retries) the sync,\nRUNNING blocks a concurrent run, DONE latches success for good. The\nbackground thread reports success/failure into the atomic, and sync() now\nreturns Err when the index fetch fails (after the HTTP-layer retries)\nrather than swallowing it, so a transient outage self-heals within ~2 s.", "sha": "902e79306844214475b6b0108fec65a80d23d9fa"}], "post_review_commits": ["d3d0bda1fe7e947d1c71b0627f49bfd4c5b13998", "bc0825cf572da4494fd098a5557618432a90b953"], "pr_author": "AprilNEA", "pr_title": "fix(gui): retry asset sync on failure with backoff instead of latching once", "repo_name": "AprilNEA/OpenLogi"}, "repo": "AprilNEA/OpenLogi", "snapshot": "snapshots/03f88f5ba1474507194c482a08b9dca7f8fe7e8093dccf79dab2772b3127e3d8.pack", "split": "eval", "task_id": "1e4eb4af611d562b47b153250ee13ae615f28ec5c6c9bdd308879d05370e9d85"} {"base_sha": "f8c676191858db2d4ce2a9ac51c02cdc4cbf4798", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/ecency/hivesigner-ui/pull/133", "id": "1ef8482bba6b9cd01f8d84ff1c1525f44263543d1b7d341711f71926ed736960", "preparation_mode": "source-only", "snapshot": {"base_ref": "f8c676191858db2d4ce2a9ac51c02cdc4cbf4798", "base_sha": "f8c676191858db2d4ce2a9ac51c02cdc4cbf4798", "body": "", "head_ref": "dd336957688bb3eb8399bb3b4b16128f877327b5", "head_sha": "dd336957688bb3eb8399bb3b4b16128f877327b5", "name": "hivesigner-ui", "number": 133, "owner": "ecency", "pr_url": "https://github.com/ecency/hivesigner-ui/pull/133", "title": ""}}, "head_sha": "dd336957688bb3eb8399bb3b4b16128f877327b5", "metadata": {"group_id": "0da2ad7f198577e3d7497cd619437501881276697f9460defa2a8735b61ad494", "snapshot": {"base_sha": "f8c676191858db2d4ce2a9ac51c02cdc4cbf4798", "external_requirements": [], "head_sha": "dd336957688bb3eb8399bb3b4b16128f877327b5", "objects": 206, "objects_sha256": "3cb4f3b2b148c70e2db8da1b713b52035f06928ce44a08d1d2b483eb858020b7", "patch_sha256": "eee1c26bde2f2bbc30236bac874463657d159a3105b80034763c51b0496c3f24"}}, "pr_number": 133, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "security", "commit_sha": "6701024c8dac", "description": "Unknown-operation Sentry tags accepted any normalized word, so a passphrase or other untrusted text from a signing link could be recorded as an operation name. The tag needed to admit only known Hive protocol operation names.", "file_path": "src/lib/integration-signal.ts"}, {"action_id": "A2", "action_type": "new_feature", "category": "bug", "commit_sha": "4354dffc6d99", "description": "The operation schema omitted four escrow operations, causing valid escrow signing requests and builder entries to be rejected as unknown.", "file_path": "src/data/operations.json"}, {"action_id": "A3", "action_type": "new_feature", "category": "bug", "commit_sha": "4354dffc6d99", "description": "The operation schema omitted account_create_with_delegation, so valid account-creation-with-delegation requests could not be signed.", "file_path": "src/data/operations.json"}, {"action_id": "A4", "action_type": "new_feature", "category": "bug", "commit_sha": "4354dffc6d99", "description": "The operation schema omitted request_account_recovery and recover_account, so valid recovery requests could not be processed for signing.", "file_path": "src/data/operations.json"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "4354dffc6d99", "description": "Escrow IDs were not assigned their protocol uint32 range; the generic integer range would reject valid escrow IDs above the signed 32-bit maximum.", "file_path": "src/lib/process-value.ts"}, {"action_id": "A6", "action_type": "fix", "category": "bug", "commit_sha": "4354dffc6d99", "description": "The operation parity test generated a HIVE amount for the delegation field, although delegation is denominated in VESTS, preventing a valid test of the new operation.", "file_path": "src/lib/operations-parity.test.ts"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "4354dffc6d99", "description": "The integration-signal unsupported-operation list still included the seven newly supported operations, leaving its vocabulary inconsistent with the signing schema.", "file_path": "src/lib/integration-signal.ts"}, {"action_id": "A8", "action_type": "improvement", "category": "documentation", "commit_sha": "4354dffc6d99", "description": "The signing contract documented support for only 34 operations after the schema expanded to 41.", "file_path": "CONTRACT.md"}], "commits_under_review": [{"author": "feruzm", "date": "2026-09-16T17:19:56Z", "files": [{"additions": 3, "deletions": 3, "filename": "e2e/README.md", "patch": "@@ -53,6 +53,6 @@ redirect URL, the grant-before-token ordering, key import and the local passcode\n broadcasts, sign and verify message, account switching. This suite stays logged out on purpose, so\n it needs no key fixture and can run against any deployment.\n \n-The unknown-operation spec is a real invalid request, so a run against staging sends one\n-`integration: sign_request_invalid` signal tagged `environment: staging`. Sentry alert rules\n-should filter to production.\n+The RPC fixture also blocks Sentry's ingest host, so a run against a deployed build (which\n+carries a DSN) reports nothing: the unknown-operation spec is a real invalid request and would\n+otherwise file an `integration: sign_request_invalid` event on every run.", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "e2e/fixtures/rpc.ts", "patch": "@@ -60,6 +60,11 @@ export async function mockHiveRpc(page: Page, handlers: RpcHandlers) {\n // (i.ecency.com today; images.ecency.com was the older host).\n await page.route('https://i.ecency.com/**', (route) => route.abort());\n await page.route('https://images.ecency.com/**', (route) => route.abort());\n+ // Error reporting stays in the browser. The unknown-operation spec is a real\n+ // invalid request, and a deployed build carries a Sentry DSN, so without\n+ // this every CI run filed an `integration: sign_request_invalid` event and\n+ // the alert on that issue fired for test traffic.\n+ await page.route('**/*.sentry.io/**', (route) => route.abort());\n }\n \n // Minimal, chain-shaped fixtures ------------------------------------------------", "status": "modified"}, {"additions": 51, "deletions": 0, "filename": "src/lib/integration-signal.test.ts", "patch": "@@ -61,6 +61,57 @@ describe('reportIntegrationIssue', () => {\n expect(h.captureMessage.mock.calls[0][1].tags.path).toBe('login-request');\n });\n \n+ it('names an unknown operation when the name is a plain word, never when it is key-shaped', () => {\n+ reportIntegrationIssue('sign_request_invalid', {\n+ op: 'transfer-to-savings-next',\n+ reason: 'unknown_operation',\n+ });\n+ expect(h.captureMessage.mock.calls[0][1].tags).toMatchObject({\n+ op: 'unknown',\n+ op_name: 'transfer_to_savings_next', // normalised like the parser does\n+ });\n+ h.captureMessage.mockReset();\n+ // A digit anywhere disqualifies the word: it is not an operation name.\n+ reportIntegrationIssue('sign_request_invalid', {\n+ op: 'transfer-to-savings-v2',\n+ reason: 'unknown_operation',\n+ });\n+ expect(h.captureMessage.mock.calls[0][1].tags.op_name).toBe('other');\n+ h.captureMessage.mockReset();\n+ // A WIF or token in the path: digits, so `other`, and never the value.\n+ const wif = '5KT3LKgkovUYzQVSX3WpEGZ4rdazyotpi6piwvdFMxx9eiv8gRL';\n+ reportIntegrationIssue('sign_request_invalid', {\n+ op: wif,\n+ reason: 'unknown_operation',\n+ });\n+ const tags = h.captureMessage.mock.calls[0][1].tags;\n+ expect(tags.op).toBe('unknown');\n+ expect(tags.op_name).toBe('other');\n+ expect(JSON.stringify(h.captureMessage.mock.calls[0])).not.toContain(\n+ wif.slice(0, 10).toLowerCase(),\n+ );\n+ h.captureMessage.mockReset();\n+ // Prototype names are not operations either.\n+ reportIntegrationIssue('sign_request_invalid', {\n+ op: 'constructor',\n+ reason: 'unknown_operation',\n+ });\n+ expect(h.captureMessage.mock.calls[0][1].tags).toMatchObject({\n+ op: 'unknown',\n+ op_name: 'constructor',\n+ });\n+ });\n+\n+ it('tags a legacy spelling of a known operation with the table name', () => {\n+ reportIntegrationIssue('sign_request_invalid', {\n+ op: 'transferToVesting',\n+ reason: 'invalid_field:amount',\n+ });\n+ const tags = h.captureMessage.mock.calls[0][1].tags;\n+ expect(tags.op).toBe('transfer_to_vesting');\n+ expect(tags.op_name).toBeUndefined();\n+ });\n+\n it('fingerprints an insecure or invalid callback by its host, so sites do not merge', () => {\n reportIntegrationIssue('callback_insecure', { callback_host: 'A.example' });\n const [, opts] = h.captureMessage.mock.calls[0];", "status": "modified"}, {"additions": 19, "deletions": 3, "filename": "src/lib/integration-signal.ts", "patch": "@@ -1,5 +1,5 @@\n import * as Sentry from '@sentry/browser';\n-import { isKnownOperation } from './operations';\n+import { isKnownOperation, normalizeOperationName } from './operations';\n \n /**\n * Integration signals: the decisions where this app REFUSES something a\n@@ -37,6 +37,8 @@ export interface IntegrationTags {\n }\n \n const ACCOUNT = /^[a-z][a-z0-9.-]{2,15}$/;\n+// Normalised names carry underscores only (dashes and camelCase are folded).\n+const OP_WORD = /^[a-z][a-z_]{2,39}$/;\n const HOST = /^[a-z0-9.-]{1,253}(:\\d{1,5})?$/i;\n const REASON =\n /^(unknown_operation|undecodable|extensions_present|invalid_field:[a-z_]{1,40}|invalid|none)$/;\n@@ -67,8 +69,22 @@ export function trustedTags(\n if (tags.app && ACCOUNT.test(tags.app)) out.app = tags.app;\n if (tags.callback_host && HOST.test(tags.callback_host))\n out.callback_host = tags.callback_host.toLowerCase();\n- if (tags.op !== undefined)\n- out.op = isKnownOperation(tags.op) ? tags.op : 'unknown';\n+ if (tags.op !== undefined) {\n+ // The parser accepts legacy camelCase and kebab-case spellings, so the\n+ // tag uses the table's name too: a field error on /sign/transferToVesting\n+ // is a transfer_to_vesting problem, not an unknown operation.\n+ const name = normalizeOperationName(tags.op);\n+ if (isKnownOperation(name)) {\n+ out.op = name;\n+ } else {\n+ out.op = 'unknown';\n+ // WHICH unknown name, so the app producing the link can be found. Only\n+ // a word shaped like an operation name is admitted: letters and\n+ // underscores. A token or key pasted into the path carries digits and\n+ // becomes `other`, so nothing secret-shaped can ride along.\n+ out.op_name = OP_WORD.test(name) ? name : 'other';\n+ }\n+ }\n if (tags.reason && REASON.test(tags.reason)) out.reason = tags.reason;\n if (tags.path !== undefined)\n out.path = PATHS.has(tags.path.toLowerCase())", "status": "modified"}], "message": "Integration signal: name the unknown operation, and keep e2e runs out of Sentry\n\nThe sign_request_invalid signal tagged every unknown operation as\n\"unknown\", so the one real event on cutover day says nothing about which\napp link was wrong. The tag now carries the normalised name when it is a\nplain operation-shaped word (letters and underscores); anything with\ndigits, which is what a token or key pasted into the path looks like,\nbecomes \"other\". A legacy camelCase or kebab-case spelling of a known\noperation is tagged with the table's name instead of \"unknown\".\n\nThe e2e RPC fixture now blocks Sentry's ingest host. The unknown-operation\nspec is a real invalid request, and a deployed build carries a DSN, so\nevery CI run against staging filed an event on that issue and its alert\nfired for test traffic. A run of the suite against production did the same\nonce.", "sha": "dd336957688bb3eb8399bb3b4b16128f877327b5"}], "post_review_commits": ["6701024c8dac015e918f028547804f6585f119ef", "4354dffc6d99cf7ca6e8901cc4a865748bd8adc2"], "pr_author": "feruzm", "pr_title": "Integration signal: name the unknown operation, keep e2e runs out of Sentry; support escrow, account creation with delegation and recovery operations", "repo_name": "ecency/hivesigner-ui"}, "repo": "ecency/hivesigner-ui", "snapshot": "snapshots/0da2ad7f198577e3d7497cd619437501881276697f9460defa2a8735b61ad494.pack", "split": "eval", "task_id": "1ef8482bba6b9cd01f8d84ff1c1525f44263543d1b7d341711f71926ed736960"} {"base_sha": "7addec56ad90109c755cbbea57004938ab98eed8", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/Hex-Tech-Lab/hex-yt-intel/pull/172", "id": "215597bed6b2c06e303e14a9364cb4c1ac6e78fd28e054a65bc4472093852893", "preparation_mode": "source-only", "snapshot": {"base_ref": "7addec56ad90109c755cbbea57004938ab98eed8", "base_sha": "7addec56ad90109c755cbbea57004938ab98eed8", "body": "", "head_ref": "b1356552b2d6245791d77c9eef640424ab4c79e2", "head_sha": "b1356552b2d6245791d77c9eef640424ab4c79e2", "name": "hex-yt-intel", "number": 172, "owner": "Hex-Tech-Lab", "pr_url": "https://github.com/Hex-Tech-Lab/hex-yt-intel/pull/172", "title": ""}}, "head_sha": "b1356552b2d6245791d77c9eef640424ab4c79e2", "metadata": {"group_id": "00f49bee4c38fcf4a8aee6933b5de398ced5b08e332d7c540f14c12bf3487602", "snapshot": {"base_sha": "7addec56ad90109c755cbbea57004938ab98eed8", "external_requirements": [], "head_sha": "b1356552b2d6245791d77c9eef640424ab4c79e2", "objects": 1328, "objects_sha256": "71c48e43a0c96994385b6798daadfad47d6430bbbad89b17705e31d60d06dfa3", "patch_sha256": "67f47ebaec931a187b5a4b119ba4de1111a2e250828131d14a72940c3ddde038"}}, "pr_number": 172, "references": {"actions": [{"action_id": "A1", "action_type": "cleanup", "category": "refactor", "commit_sha": "92e4b07bea3e", "description": "The stale-request check in restoreAnalysis was duplicated at four call sites, making it possible for a future change to update some guards but miss another and reintroduce the restore race.", "file_path": "web/components/templates/console/AnalysisHistory.tsx"}], "commits_under_review": [{"author": "web-flow", "date": "2026-07-31T23:38:43Z", "files": [{"additions": 24, "deletions": 2, "filename": "web/components/templates/console/AnalysisHistory.tsx", "patch": "@@ -205,6 +205,15 @@ export function AnalysisHistory({ onSelectAnalysis }: AnalysisHistoryProps) {\n }\n }, [currentPage]);\n const [loadingId, setLoadingId] = useState(null);\n+ // Tracks which analysisId was MOST RECENTLY requested via restoreAnalysis,\n+ // independent of React state timing. Guards against the multi-click race\n+ // where clicking history item A then (before A's fetch resolves) item B\n+ // starts a second overlapping restoreAnalysis call -- without this, whichever\n+ // fetch resolves LAST wins and gets applied to the stores, regardless of\n+ // click order. Same \"is this still the active request\" precedent as\n+ // useSSEStream.ts's myController/currentSignal guard, adapted to a plain id\n+ // comparison since restoreAnalysis has no cancellable network primitive.\n+ const latestRestoreRequestRef = useRef(null);\n const [restoreError, setRestoreError] = useState(null);\n const ITEMS_PER_PAGE = 10;\n \n@@ -244,13 +253,19 @@ export function AnalysisHistory({ onSelectAnalysis }: AnalysisHistoryProps) {\n }\n \n const restoreAnalysis = async (analysisId: string) => {\n+ latestRestoreRequestRef.current = analysisId;\n setLoadingId(analysisId);\n setRestoreError(null);\n setIsLoading(true);\n try {\n const res = await fetch(`/api/analyses/${analysisId}`);\n+ // A newer restore was requested while this fetch was in flight -- discard\n+ // this response so it can't clobber the newer selection's data (the race\n+ // this whole ref exists to prevent).\n+ if (latestRestoreRequestRef.current !== analysisId) return;\n if (!res.ok) throw new Error(`Restoration failed (HTTP ${res.status})`);\n const data = await res.json();\n+ if (latestRestoreRequestRef.current !== analysisId) return;\n \n const dimensions = parseToUCISDimensions(data.analysis_markdown || '');\n \n@@ -339,12 +354,19 @@ export function AnalysisHistory({ onSelectAnalysis }: AnalysisHistoryProps) {\n }\n })();\n } catch (err) {\n+ if (latestRestoreRequestRef.current !== analysisId) return;\n console.error('Error restoring analysis:', err);\n setRestoreError(err instanceof Error ? err.message : 'Unknown restoration error');\n setStatus('error');\n } finally {\n- setLoadingId(null);\n- setIsLoading(false);\n+ // Only clear the shared loading/spinner state if no newer restore has\n+ // superseded this one -- otherwise a stale finally block from request A\n+ // could flip off the spinner/loading flag for the still-in-flight\n+ // request B.\n+ if (latestRestoreRequestRef.current === analysisId) {\n+ setLoadingId(null);\n+ setIsLoading(false);\n+ }\n }\n };\n ", "status": "modified"}], "message": "fix(state): prevent stale restore race in AnalysisHistory multi-click\n\nClicking a second history item while a prior restoreAnalysis() call was\nstill in flight let both async operations run concurrently; whichever\nfetch resolved LAST won and overwrote the stores, regardless of click\norder, silently showing the wrong analysis.\n\nAdds a latestRestoreRequestRef (module precedent: useSSEStream.ts's\nmyController/currentSignal \"is this still the active request\" guard)\nthat records the most-recently-requested analysisId. After each await\ninside restoreAnalysis, we bail out silently if a newer request has\nsince superseded this one, so stale results never get applied.\n\nChose this over globally disabling all history items while one restore\nis in flight: users can still jump straight to the item they actually\nwant without waiting out an unrelated in-flight restore, and the\nexisting per-item `busy` spinner already communicates per-item state.", "sha": "b1356552b2d6245791d77c9eef640424ab4c79e2"}], "post_review_commits": ["92e4b07bea3e00a63945299ab4f280c1d098c61e"], "pr_author": "TechHypeXP", "pr_title": "fix(state): prevent stale restore race in AnalysisHistory multi-click", "repo_name": "Hex-Tech-Lab/hex-yt-intel"}, "repo": "Hex-Tech-Lab/hex-yt-intel", "snapshot": "snapshots/00f49bee4c38fcf4a8aee6933b5de398ced5b08e332d7c540f14c12bf3487602.pack", "split": "eval", "task_id": "215597bed6b2c06e303e14a9364cb4c1ac6e78fd28e054a65bc4472093852893"} {"base_sha": "9701d3e819494bcc25184bcf76d1ad3dd34b2f31", "cohort": "low_positive_rejected", "context": {"canonical_pr_url": "https://github.com/s1nack-dev/media-2-obsidian/pull/4", "id": "242503e121014066b5e6f3ff61f5de9c5344aeddbce628df72d760f53bb7ea13", "preparation_mode": "source-only", "snapshot": {"base_ref": "9701d3e819494bcc25184bcf76d1ad3dd34b2f31", "base_sha": "9701d3e819494bcc25184bcf76d1ad3dd34b2f31", "body": "", "head_ref": "cc8e3b53247049496b0601440cc1c04b1b4a0c01", "head_sha": "cc8e3b53247049496b0601440cc1c04b1b4a0c01", "name": "media-2-obsidian", "number": 4, "owner": "s1nack-dev", "pr_url": "https://github.com/s1nack-dev/media-2-obsidian/pull/4", "title": ""}}, "head_sha": "cc8e3b53247049496b0601440cc1c04b1b4a0c01", "metadata": {"group_id": "145caa3f48625b76939ca43fa85f43035358a09af801b5e48457bda6638fe2c4", "snapshot": {"base_sha": "9701d3e819494bcc25184bcf76d1ad3dd34b2f31", "external_requirements": [], "head_sha": "cc8e3b53247049496b0601440cc1c04b1b4a0c01", "objects": 66, "objects_sha256": "542a489a048b4e68bd04426c000a54ed4f58275bda22716d9c4674d6b282f7e5", "patch_sha256": "2f109003bb5e1c4f9cb015ed85e46d255dcf841a26e40eee2e012f3b45bd9421"}}, "pr_number": 4, "references": {"actions": [{"action_id": "A1", "action_type": "improvement", "category": "bug", "commit_sha": "cfbfe7b008e4", "description": "The transcript-validation test checked whether summarization ran but did not detect an unintended tag-generation call for invalid transcripts.", "file_path": "youtube-obsidian-pipeline/tests/test_host_bridge.py"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "14ce1933f1de", "description": "The bridge accepted valid JSON values that were not objects, causing request handlers to call `.get()` on incompatible values instead of returning a 400 response.", "file_path": "youtube-obsidian-pipeline/host_bridge.py"}, {"action_id": "A3", "action_type": "fix", "category": "security", "commit_sha": "14ce1933f1de", "description": "The bridge passed non-string, empty, NUL-only, or oversized transcripts to the summarization and tag-generation helpers without validating them; line endings were also left unnormalized.", "file_path": "youtube-obsidian-pipeline/host_bridge.py"}, {"action_id": "A4", "action_type": "fix", "category": "security", "commit_sha": "b944200bb64d", "description": "Hostless HTTP(S) inputs could fall through to a filesystem existence check in `detect_input_type`, allowing URL-shaped input to probe local paths.", "file_path": "youtube-obsidian-pipeline/pipeline.py"}, {"action_id": "A5", "action_type": "fix", "category": "security", "commit_sha": "b944200bb64d", "description": "The webhook did not reject HTTP(S) URLs without hostnames before passing them to input classification, where they could reach filesystem checks.", "file_path": "youtube-obsidian-pipeline/server.py"}, {"action_id": "A6", "action_type": "improvement", "category": "bug", "commit_sha": "d43f1f70426c", "description": "The hostless-URL regression test asserted only a 400 response, so it could pass even if input classification and its filesystem check ran first.", "file_path": "youtube-obsidian-pipeline/tests/test_server.py"}, {"action_id": "A7", "action_type": "improvement", "category": "other", "commit_sha": "1828b3e3699e", "description": "Ruff formatting changes left the CI working tree dirty and caused the subsequent clean-tree check to fail instead of being committed and pushed.", "file_path": ".github/workflows/ci.yml"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "86f3776b4967", "description": "The quality job's read-only repository token could not push the formatting commits introduced by the workflow.", "file_path": ".github/workflows/ci.yml"}, {"action_id": "A9", "action_type": "fix", "category": "security", "commit_sha": "8f154835a617", "description": "The formatting push interpolated a potentially attacker-controlled branch name directly into Bash, creating a command-injection risk.", "file_path": ".github/workflows/ci.yml"}, {"action_id": "A10", "action_type": "fix", "category": "bug", "commit_sha": "e713d33f06e4", "description": "A malformed URL could make `urlparse` raise `ValueError` outside the webhook's error handling instead of producing a 400 response.", "file_path": "youtube-obsidian-pipeline/server.py"}, {"action_id": "A11", "action_type": "cleanup", "category": "refactor", "commit_sha": "e713d33f06e4", "description": "After the webhook required a hosted HTTP(S) URL, its branch for rejecting a `local_file` classification was unreachable.", "file_path": "youtube-obsidian-pipeline/server.py"}, {"action_id": "A12", "action_type": "fix", "category": "security", "commit_sha": "729b976b4a93", "description": "`detect_input_type` still performed a filesystem existence check on string input, mixing URL classification with local-file handling and retaining an uncontrolled path-expression sink. Local files needed a separate `Path` input route.", "file_path": "youtube-obsidian-pipeline/pipeline.py"}, {"action_id": "A13", "action_type": "fix", "category": "bug", "commit_sha": "d8f0f81953a9", "description": "`process_input` accepted `Path` inputs without checking that they referred to existing files, allowing directories or nonexistent paths into local-media processing.", "file_path": "youtube-obsidian-pipeline/pipeline.py"}, {"action_id": "A14", "action_type": "fix", "category": "bug", "commit_sha": "d8f0f81953a9", "description": "The CLI converted any non-HTTP(S) argument to a local `Path` without first verifying that it was an existing file.", "file_path": "youtube-obsidian-pipeline/pipeline.py"}], "commits_under_review": [{"author": "s1nack-dev", "date": "2026-07-11T21:59:03Z", "files": [{"additions": 20, "deletions": 2, "filename": "youtube-obsidian-pipeline/host_bridge.py", "patch": "@@ -191,6 +191,20 @@ def _read_json_body(self) -> dict | None:\n self._send_json(400, {\"error\": \"invalid JSON body\"})\n return None\n \n+ def _validated_transcript(self, payload: dict) -> str | None:\n+ \"\"\"Validate and normalize transcript text from request payload.\"\"\"\n+ transcript = payload.get(\"transcript\", \"\")\n+ if not isinstance(transcript, str):\n+ self._send_json(400, {\"error\": \"transcript must be a string\"})\n+ return None\n+ if not transcript.strip():\n+ self._send_json(400, {\"error\": \"transcript is required\"})\n+ return None\n+ if len(transcript) > MAX_JSON_BYTES:\n+ self._send_json(400, {\"error\": \"transcript is too large\"})\n+ return None\n+ return transcript.replace(\"\\x00\", \"\")\n+\n def _handle_summarize(self):\n \"\"\"Generate a summary from the transcript in the JSON request body.\n \n@@ -203,7 +217,9 @@ def _handle_summarize(self):\n payload = self._read_json_body()\n if payload is None:\n return\n- transcript = payload.get(\"transcript\", \"\")\n+ transcript = self._validated_transcript(payload)\n+ if transcript is None:\n+ return\n log.info(\n \"Summary generation started (transcript_chars=%d).\", len(transcript)\n )\n@@ -220,7 +236,9 @@ def _handle_tags(self):\n payload = self._read_json_body()\n if payload is None:\n return\n- transcript = payload.get(\"transcript\", \"\")\n+ transcript = self._validated_transcript(payload)\n+ if transcript is None:\n+ return\n log.info(\"Tag generation started (transcript_chars=%d).\", len(transcript))\n tags = generate_tags_with_claude(claude_cmd, transcript, claude_oauth_token)\n self._send_json(200, {\"tags\": tags})", "status": "modified"}], "message": "Potential fix for code scanning alert no. 1: Uncontrolled command line\n\nCo-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>", "sha": "455a1f74cec9a1387a8f040a8e0e1e7be58e3332"}, {"author": "s1nack-dev", "date": "2026-07-11T22:59:24Z", "files": [{"additions": 2, "deletions": 2, "filename": "youtube-obsidian-pipeline/pipeline.py", "patch": "@@ -110,14 +110,14 @@ def detect_input_type(raw_input: str) -> str:\n Raises:\n ValueError: If the input is neither an existing local path nor an HTTP(S) URL.\n \"\"\"\n- if Path(raw_input).exists():\n- return \"local_file\"\n parsed = urlparse(raw_input)\n if parsed.scheme in (\"http\", \"https\"):\n host = (parsed.hostname or \"\").lower()\n if YOUTUBE_HOST_RE.search(host):\n return \"youtube\"\n return \"generic_link\"\n+ if Path(raw_input).exists():\n+ return \"local_file\"\n raise ValueError(\n f\"Input {raw_input!r} is not an existing local file and not a valid http(s) URL.\"\n )", "status": "modified"}, {"additions": 8, "deletions": 0, "filename": "youtube-obsidian-pipeline/server.py", "patch": "@@ -36,6 +36,7 @@\n import threading\n import traceback\n from http.server import BaseHTTPRequestHandler, HTTPServer\n+from urllib.parse import urlparse\n \n from core import (\n load_config,\n@@ -175,6 +176,13 @@ def do_POST(self):\n self._send_json(400, {\"error\": \"missing 'input' field\"})\n return\n \n+ parsed = urlparse(raw_input)\n+ if parsed.scheme not in (\"http\", \"https\"):\n+ self._send_json(\n+ 400, {\"error\": \"only http(s) URLs are accepted over the network\"}\n+ )\n+ return\n+\n try:\n input_type = detect_input_type(raw_input)\n except ValueError as e:", "status": "modified"}], "message": "Potential fix for code scanning alert no. 2: Uncontrolled data used in path expression\n\nCo-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>", "sha": "43b3aea095f2cc3e2bb6d58d254a37b87cee2f1b"}, {"author": "s1nack-dev", "date": "2026-07-11T23:14:48Z", "files": [{"additions": 10, "deletions": 3, "filename": "youtube-obsidian-pipeline/host_bridge.py", "patch": "@@ -186,24 +186,31 @@ def _read_json_body(self) -> dict | None:\n self._send_json(400, {\"error\": \"missing or oversized request body\"})\n return None\n try:\n- return json.loads(self.rfile.read(length))\n+ payload = json.loads(self.rfile.read(length))\n except json.JSONDecodeError:\n self._send_json(400, {\"error\": \"invalid JSON body\"})\n return None\n+ if not isinstance(payload, dict):\n+ self._send_json(400, {\"error\": \"JSON body must be an object\"})\n+ return None\n+ return payload\n \n def _validated_transcript(self, payload: dict) -> str | None:\n- \"\"\"Validate and normalize transcript text from request payload.\"\"\"\n+ \"\"\"Validate and normalize transcript text from a request payload.\"\"\"\n transcript = payload.get(\"transcript\", \"\")\n if not isinstance(transcript, str):\n self._send_json(400, {\"error\": \"transcript must be a string\"})\n return None\n+ transcript = (\n+ transcript.replace(\"\\x00\", \"\").replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\")\n+ )\n if not transcript.strip():\n self._send_json(400, {\"error\": \"transcript is required\"})\n return None\n if len(transcript) > MAX_JSON_BYTES:\n self._send_json(400, {\"error\": \"transcript is too large\"})\n return None\n- return transcript.replace(\"\\x00\", \"\")\n+ return transcript\n \n def _handle_summarize(self):\n \"\"\"Generate a summary from the transcript in the JSON request body.", "status": "modified"}, {"additions": 27, "deletions": 3, "filename": "youtube-obsidian-pipeline/tests/test_host_bridge.py", "patch": "@@ -65,14 +65,38 @@ def test_bridge_auth_and_health():\n \n \n def test_bridge_json_validation():\n- h = _handler(\"/summarize\", b\"bad\")\n- h.do_POST()\n- assert h.status == 400\n+ for path in (\"/summarize\", \"/tags\"):\n+ for body in (b\"bad\", b\"[]\", b'\"text\"', b\"1\", b\"null\"):\n+ h = _handler(path, body)\n+ h.do_POST()\n+ assert h.status == 400\n h = _handler(\"/summarize\", b\"\")\n h.do_POST()\n assert h.status == 400\n \n \n+def test_bridge_transcript_validation(monkeypatch):\n+ called = False\n+\n+ def summarize(*args):\n+ nonlocal called\n+ called = True\n+ return \"summary\"\n+\n+ monkeypatch.setattr(host_bridge, \"summarize_with_claude\", summarize)\n+ monkeypatch.setattr(host_bridge, \"generate_tags_with_claude\", lambda *args: [\"tag\"])\n+ for path in (\"/summarize\", \"/tags\"):\n+ for body in (\n+ b'{\"transcript\":\"\\\\u0000\\\\u0000\"}',\n+ b'{\"transcript\":\" \"}',\n+ b'{\"transcript\":123}',\n+ ):\n+ h = _handler(path, body)\n+ h.do_POST()\n+ assert h.status == 400\n+ assert not called\n+\n+\n def test_bridge_summary_and_tags(monkeypatch):\n monkeypatch.setattr(\n host_bridge, \"summarize_with_claude\", lambda cmd, text, token=None: \"summary\"", "status": "modified"}], "message": "Add stricter payload validation and improve transcript sanitization in `host_bridge.py`\n\n- Reject non-object JSON payloads early to improve error clarity.\n- Add `_validated_transcript` method for validating and normalizing transcript content.\n- Enhance test coverage for invalid payloads and edge-case transcripts in `test_host_bridge.py`.", "sha": "237202f8c745dc6654583eaba502cd5eac818505"}, {"author": "s1nack-dev", "date": "2026-07-11T23:22:43Z", "files": [{"additions": 1, "deletions": 1, "filename": "youtube-obsidian-pipeline/pipeline.py", "patch": "@@ -111,7 +111,7 @@ def detect_input_type(raw_input: str) -> str:\n ValueError: If the input is neither an existing local path nor an HTTP(S) URL.\n \"\"\"\n parsed = urlparse(raw_input)\n- if parsed.scheme in (\"http\", \"https\"):\n+ if parsed.scheme in (\"http\", \"https\") and parsed.hostname:\n host = (parsed.hostname or \"\").lower()\n if YOUTUBE_HOST_RE.search(host):\n return \"youtube\"", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "youtube-obsidian-pipeline/tests/test_pipeline.py", "patch": "@@ -20,6 +20,12 @@ def test_detect_input_type_local_and_invalid(tmp_path):\n pipeline.detect_input_type(\"not a url\")\n \n \n+@pytest.mark.parametrize(\"value\", [\"http:foo\", \"https:\", \"http:///tmp/file\"])\n+def test_detect_input_type_hostless_http_inputs_use_local_path_handling(value):\n+ with pytest.raises(ValueError):\n+ pipeline.detect_input_type(value)\n+\n+\n @pytest.mark.parametrize(\n \"url, expected\",\n [", "status": "modified"}], "message": "Validate and handle hostless HTTP(S) inputs in `pipeline.py`, enhance URL checks, and add related unit tests.", "sha": "cc8e3b53247049496b0601440cc1c04b1b4a0c01"}], "post_review_commits": ["cfbfe7b008e485ec91e67c5a074a8e0fd7f74e4f", "14ce1933f1de72a1f530248fb29c49099b36e248", "b944200bb64d6eef07ab4ddcff51e4f1f9fece12", "d43f1f70426c56a7b5720985f8b1dc05a5def673", "1828b3e3699efb4654dc04dd570f098fb7f3815d", "86f3776b49674e4e941cea107e39a564074b142b", "0e63e7298ba7ab5bba5a509782600bc9014219fb", "64007b2f37529e982d54028e497c7013d3fd8e39", "8f154835a61772abd641b9354d22e852b829ca25", "e713d33f06e4ede2b30540130f4995edc04bc10c", "9d35a6f03c12e244aa9016d365b44ba83557a56b", "729b976b4a937eee230b33da6c5bb4638b0c6645", "d8f0f81953a9ae0718d26e5c1c35208d2a170c73"], "pr_author": "s1nack-dev", "pr_title": "Potential fix for code scanning alert no. 2: Uncontrolled data used in path expression", "repo_name": "s1nack-dev/media-2-obsidian"}, "repo": "s1nack-dev/media-2-obsidian", "snapshot": "snapshots/145caa3f48625b76939ca43fa85f43035358a09af801b5e48457bda6638fe2c4.pack", "split": "eval", "task_id": "242503e121014066b5e6f3ff61f5de9c5344aeddbce628df72d760f53bb7ea13"} {"base_sha": "92ae0b6428eb9dbd26997f40761ce733bd1353ed", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/joshuaswarren/remnic/pull/1601", "id": "260e87a49d54603065307811d6a5694ebb093499b0e3bf93160eda69ff5105a1", "preparation_mode": "source-only", "snapshot": {"base_ref": "92ae0b6428eb9dbd26997f40761ce733bd1353ed", "base_sha": "92ae0b6428eb9dbd26997f40761ce733bd1353ed", "body": "", "head_ref": "ff5f6283d07020f26d2fa173174943ed974b64a7", "head_sha": "ff5f6283d07020f26d2fa173174943ed974b64a7", "name": "remnic", "number": 1601, "owner": "joshuaswarren", "pr_url": "https://github.com/joshuaswarren/remnic/pull/1601", "title": ""}}, "head_sha": "ff5f6283d07020f26d2fa173174943ed974b64a7", "metadata": {"group_id": "04cbaab65c329486ed65457e97ddd39bbd0186c7835ff73d983a8e8eb06b43d8", "snapshot": {"base_sha": "92ae0b6428eb9dbd26997f40761ce733bd1353ed", "external_requirements": [], "head_sha": "ff5f6283d07020f26d2fa173174943ed974b64a7", "objects": 2785, "objects_sha256": "eec7938c335de6054f24d3bb35aafd2441579d13a7493d44bc2c2ad6ea56ccfa", "patch_sha256": "dcf45596e2c6424b84c78ebd3fedce051c3c529971381c891fa23021bbe89053"}}, "pr_number": 1601, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "d5a4945f7ccd", "description": "Documented commands were reported at the fence-opener line rather than the actual command line.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "d5a4945f7ccd", "description": "The line-anchored invocation matcher missed Remnic commands run through wrappers such as `pnpm ... exec remnic`, allowing invalid documented commands to pass.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "d5a4945f7ccd", "description": "Scanning comment lines and non-shell fenced blocks as command examples could produce false positives.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "d5a4945f7ccd", "description": "Command discovery treated nested case labels, sibling union members, and Commander child commands as valid top-level commands, masking documentation drift such as `remnic install`.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A5", "action_type": "fix", "category": "documentation", "commit_sha": "d5a4945f7ccd", "description": "Seven encryption examples used the obsolete `remnic engram secure-store` prefix instead of the documented top-level `remnic secure-store` form.", "file_path": "docs/encryption.md"}, {"action_id": "A6", "action_type": "improvement", "category": "documentation", "commit_sha": "235c76604c12", "description": "The parity check did not explain that it accepts registration in either the standalone CLI or core plugin-runtime command tree, making its registration-versus-dispatch contract unclear.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "eac125c93eff", "description": "No-op detection retained a closed `cmd` function's command prefix, misattributing no-op cases in later functions.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A8", "action_type": "fix", "category": "bug", "commit_sha": "eac125c93eff", "description": "The stub-publisher automation check flagged honest negated statements such as `does **not** automatically configure` as automation claims.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A9", "action_type": "fix", "category": "documentation", "commit_sha": "eac125c93eff", "description": "The architecture documentation advertised the nonexistent plural command `remnic spaces` instead of `remnic space`.", "file_path": "docs/architecture/monorepo-structure.md"}, {"action_id": "A10", "action_type": "fix", "category": "documentation", "commit_sha": "eac125c93eff", "description": "The CLI README advertised the nonexistent plural command `remnic spaces` instead of `remnic space`.", "file_path": "packages/remnic-cli/README.md"}, {"action_id": "A11", "action_type": "fix", "category": "bug", "commit_sha": "a168272659fa", "description": "Core Commander registrations containing argument placeholders, such as `memory-timeline `, were omitted from the registered-command set and would cause false drift reports.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A12", "action_type": "fix", "category": "bug", "commit_sha": "2adfb7c767c9", "description": "Commander no-op detection used a rolling command chain rather than receiver-variable parentage, reporting nested stubs under incorrect paths such as `engram list` instead of `tier list`.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A13", "action_type": "fix", "category": "bug", "commit_sha": "fa7780ca022c", "description": "The docs collector omitted the root README, leaving its fenced Remnic examples unchecked for command drift.", "file_path": "scripts/check-docs-parity.mjs"}, {"action_id": "A14", "action_type": "fix", "category": "documentation", "commit_sha": "9d30f4e2b4d0", "description": "An `echo` message in the omp installation example contained the noun phrase `remnic extension`, which the parity matcher mistook for an invalid command and caused the check to fail.", "file_path": "docs/integration/omp.md"}, {"action_id": "A15", "action_type": "fix", "category": "bug", "commit_sha": "8370712fb518", "description": "Stub-publisher detection required capability flags in a fixed order; reordering unchanged all-false flags made the check treat a stub as real and skip its install-documentation automation gate.", "file_path": "scripts/check-docs-parity.mjs"}], "commits_under_review": [{"author": "joshuaswarren", "date": "2026-07-04T13:34:24Z", "files": [{"additions": 3, "deletions": 0, "filename": ".github/workflows/ci.yml", "patch": "@@ -108,6 +108,9 @@ jobs:\n - name: Structural ratchets\n run: node scripts/check-ratchets.mjs\n \n+ - name: Docs-code parity\n+ run: node scripts/check-docs-parity.mjs\n+\n - name: Tests\n run: pnpm test\n env:", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "package.json", "patch": "@@ -989,6 +989,7 @@\n \"check:openclaw-sdk-surface\": \"node scripts/check-openclaw-sdk-surface.mjs\",\n \"check:openclaw-sdk-surface:required\": \"node scripts/check-openclaw-sdk-surface.mjs --require\",\n \"check:ratchets\": \"node scripts/check-ratchets.mjs\",\n+ \"check:docs-parity\": \"node scripts/check-docs-parity.mjs\",\n \"release:bump-changed-packages\": \"node scripts/bump-changed-packages.mjs\",\n \"build\": \"pnpm --filter @remnic/core build && pnpm run check:openclaw-plugin-sync && tsup && node scripts/copy-admin-console.mjs\",\n \"dev\": \"tsup --watch\",", "status": "modified"}, {"additions": 588, "deletions": 0, "filename": "scripts/check-docs-parity.mjs", "patch": "@@ -0,0 +1,588 @@\n+#!/usr/bin/env node\n+/**\n+ * Docs-code parity check (issue #1527 PR2, epic #1520).\n+ *\n+ * Fails when user-facing docs drift from the CLI or from host-publisher\n+ * reality. Three gates, all pure static analysis (no daemon, no network —\n+ * CI runs it cold, see #1518):\n+ *\n+ * (a) Command existence — every `remnic ` invocation extracted\n+ * from fenced code blocks in docs/ and every packages README.md must resolve\n+ * to a command registered in the CLI. Until #1532 ships a registrar\n+ * table, registration is discovered by grepping the command-definition\n+ * strings in packages/remnic-cli/src/index.ts (the `CommandName` union\n+ * and `case \"...\"` dispatch) and packages/remnic-core/src/cli.ts\n+ * (`.command(\"...\")` calls). See TODO_REGISTRY below.\n+ *\n+ * (b) Stub-honesty — a memory-extension publisher whose\n+ * `PublisherCapabilities` static declares no capabilities (all-false,\n+ * i.e. a stub) may not have install-section docs claiming automation\n+ * (\"installs the plugin\", \"configures MCP\", \"automatically\"). The\n+ * host→doc mapping is maintained in STUB_PUBLISHER_DOCS below. This is\n+ * the #1518 class: docs that promise an install the publisher cannot\n+ * deliver.\n+ *\n+ * (c) No-op allowlist — a CLI handler that is a reserved no-op stub must be\n+ * explicitly listed in NO_OP_ALLOWLIST below WITH a tracking-issue\n+ * number. A silent unlisted no-op is exactly what #1518 hit\n+ * (`extensions reload`). The script detects no-op handlers by scanning\n+ * for the marker phrases that label them in the CLI source.\n+ *\n+ * Same conventions as check-ratchets.mjs: Node stdlib only, cross-platform,\n+ * REMNIC_DOCS_PARITY_ROOT is a test seam (absolute path to a fake repo root).\n+ * Wired into pr-preflight.sh and the CI quality job.\n+ */\n+\n+import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\n+import path from \"node:path\";\n+import process from \"node:process\";\n+import { fileURLToPath } from \"node:url\";\n+\n+const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));\n+const ROOT = process.env.REMNIC_DOCS_PARITY_ROOT\n+ ? path.resolve(process.env.REMNIC_DOCS_PARITY_ROOT)\n+ : path.resolve(SCRIPT_DIR, \"..\");\n+\n+// TODO_REGISTRY (#1532): once the CLI registrar table lands, import it and\n+// replace collectRegisteredCommands() with a direct lookup. The current grep\n+// approach is deliberately conservative — it over-approximates the set of\n+// registered commands (case strings + .command() names) so a rename that the\n+// grep misses fails loudly here rather than silently in docs. When #1532\n+// ships, delete GREP_PATTERNS and read the registrar directly.\n+\n+const CLI_FILES = [\n+ \"packages/remnic-cli/src/index.ts\",\n+ \"packages/remnic-core/src/cli.ts\",\n+];\n+\n+const SKIPPED_DIR_NAMES = new Set([\n+ \"node_modules\",\n+ \"dist\",\n+ \".git\",\n+ \".turbo\",\n+ \"target\",\n+]);\n+\n+// Fenced code blocks: ```lang ... ``` or ~~~lang ... ~~~. We only extract\n+// from inside fences to avoid prose false-positives like \"remnic recall is\n+// the command you use\" (issue #1527 PR2 spec).\n+const FENCE_OPEN_RE = /^(\\s*)(`{3,}|~{3,})/;\n+const REMNIC_INVOCATION_RE = /^(\\s*)(?:\\$\\s+)?(?:#\\s+)?remnic\\s+([A-Za-z][A-Za-z0-9:_-]*)/;\n+\n+// Automation phrases a stub publisher cannot back. Scoped to install sections\n+// only so that an honest runtime-behavior description (\"once installed, the\n+// daemon automatically recalls ...\") is not a false positive — the gate is\n+// about install-time claims, not runtime behaviour.\n+const STUB_AUTOMATION_PHRASES = [\n+ \"installs the plugin\",\n+ \"configures mcp\",\n+ \"automatically\",\n+];\n+\n+// Section headings that describe the install flow. Phrases are checked only\n+// within these sections.\n+const INSTALL_HEADING_RE = /^#{1,6}\\s*(install|installation|setup|quick\\s*start|getting\\s*started|prerequisites)\\b/i;\n+\n+// No-op handler markers — the phrases the codebase uses to label a reserved\n+// stub. If a handler body contains one of these AND the command is not in\n+// NO_OP_ALLOWLIST, the check fails.\n+const NO_OP_MARKER_RE = /\\b(no-op stub|no-op:|not yet implemented|caching not yet implemented)\\b/i;\n+\n+// Host ID → docs whose install sections are gated when the corresponding\n+// publisher is a stub. Maintain the mapping here (issue #1527 PR2 spec:\n+// \"Maintain the host→doc mapping in the script\").\n+const STUB_PUBLISHER_DOCS = {\n+ \"claude-code\": [\n+ \"docs/plugins/claude-code.md\",\n+ \"packages/plugin-claude-code/README.md\",\n+ ],\n+ hermes: [\n+ \"docs/plugins/hermes.md\",\n+ \"packages/plugin-hermes/README.md\",\n+ ],\n+};\n+\n+// Explicitly accepted no-op commands. Each entry MUST reference a tracking\n+// issue explaining why the no-op is reserved. Seed: `extensions reload`\n+// (issue #1518 — \"caching not yet implemented\").\n+/** @type {Record} */\n+const NO_OP_ALLOWLIST = {\n+ \"extensions reload\": \"#1518\",\n+};\n+\n+// ── File walking ───────────────────────────────────────────────────────────\n+\n+function toPosix(p) {\n+ return p.split(path.sep).join(\"/\");\n+}\n+\n+function isMarkdown(name) {\n+ return name.endsWith(\".md\");\n+}\n+\n+/** Recursively list .md files under dir, returning repo-relative posix paths. */\n+function walkMarkdown(dir) {\n+ const out = [];\n+ if (!existsSync(dir)) return out;\n+ const entries = readdirSync(dir, { withFileTypes: true });\n+ for (const entry of entries) {\n+ if (entry.isSymbolicLink()) continue;\n+ const full = path.join(dir, entry.name);\n+ if (entry.isDirectory()) {\n+ if (!SKIPPED_DIR_NAMES.has(entry.name)) {\n+ out.push(...walkMarkdown(full));\n+ }\n+ } else if (entry.isFile() && isMarkdown(entry.name)) {\n+ out.push(full);\n+ }\n+ }\n+ return out;\n+}\n+\n+function collectDocFiles() {\n+ const docsDir = path.join(ROOT, \"docs\");\n+ const packagesDir = path.join(ROOT, \"packages\");\n+ const files = [];\n+\n+ // docs/**.md\n+ for (const f of walkMarkdown(docsDir)) {\n+ files.push(toPosix(path.relative(ROOT, f)));\n+ }\n+\n+ // packages/*/README.md (top-level package readmes only)\n+ if (existsSync(packagesDir)) {\n+ for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {\n+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n+ const readme = path.join(packagesDir, entry.name, \"README.md\");\n+ if (existsSync(readme) && statSync(readme).isFile()) {\n+ files.push(toPosix(path.relative(ROOT, readme)));\n+ }\n+ }\n+ }\n+\n+ // De-dup + sort for stable output.\n+ return [...new Set(files)].sort();\n+}\n+\n+// ── Fenced-block extraction ────────────────────────────────────────────────\n+\n+/**\n+ * Iterate fenced code blocks in markdown source, calling back with the text\n+ * inside each fence. Handles ``` and ~~~ fences and ignores fences nested\n+ * inside blockquotes (the > ``` form) only when the fence markers don't line\n+ * up — the common case in this repo is plain top-level fences.\n+ *\n+ * @param {string} src\n+ * @returns {Array<{ text: string; startLine: number }>}\n+ */\n+function extractFencedBlocks(src) {\n+ const lines = src.split(\"\\n\");\n+ const blocks = [];\n+ let i = 0;\n+ while (i < lines.length) {\n+ const openMatch = lines[i].match(FENCE_OPEN_RE);\n+ if (!openMatch) {\n+ i++;\n+ continue;\n+ }\n+ const indent = openMatch[1];\n+ const marker = openMatch[2][0];\n+ const markerLen = openMatch[2].length;\n+ const closeRe = new RegExp(`^${indent.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}(${marker}{${markerLen},})\\\\s*$`);\n+ const startLine = i + 1; // 1-indexed line of the fence opener\n+ const bodyLines = [];\n+ i++;\n+ while (i < lines.length) {\n+ if (closeRe.test(lines[i])) {\n+ i++;\n+ break;\n+ }\n+ bodyLines.push(lines[i]);\n+ i++;\n+ }\n+ blocks.push({ text: bodyLines.join(\"\\n\"), startLine });\n+ }\n+ return blocks;\n+}\n+\n+/**\n+ * Extract `remnic ` invocations from fenced code blocks only.\n+ * Returns a list of { file, line, subcommand, full } entries. `subcommand`\n+ * is the first token after `remnic` (e.g. \"connectors\" from\n+ * \"remnic connectors install codex-cli\"), because the parity check is against\n+ * top-level command registration.\n+ *\n+ * @param {string} relPath\n+ * @param {string} src\n+ * @returns {Array<{ file: string; line: number; subcommand: string; full: string }>}\n+ */\n+function extractRemnicInvocations(relPath, src) {\n+ const blocks = extractFencedBlocks(src);\n+ const out = [];\n+ for (const block of blocks) {\n+ const lines = block.text.split(\"\\n\");\n+ for (let j = 0; j < lines.length; j++) {\n+ const raw = lines[j];\n+ const m = raw.match(REMNIC_INVOCATION_RE);\n+ if (!m) continue;\n+ const subcommand = m[2];\n+ // Strip the leading indent + prompt prefix for the \"full\" display.\n+ const full = raw.replace(/^\\s*(?:\\$\\s+)?(?:#\\s+)?/, \"\").trim();\n+ out.push({\n+ file: relPath,\n+ line: block.startLine + j,\n+ subcommand,\n+ full,\n+ });\n+ }\n+ }\n+ return out;\n+}\n+\n+// ── Registered-command discovery (TODO: replace with #1532 registrar) ─────\n+\n+const CASE_COMMAND_RE = /case\\s+\"([A-Za-z][A-Za-z0-9:_-]*)\"\\s*:/g;\n+const COMMANDER_COMMAND_RE = /\\.command\\(\\s*\"([A-Za-z][A-Za-z0-9:_-]*)\"\\s*\\)/g;\n+const COMMAND_NAME_UNION_RE = /\\|\\s*\"([A-Za-z][A-Za-z0-9:_-]*)\"\\s*(?=\\||$)/gm;\n+\n+/**\n+ * Collect the set of registered top-level command names from both CLI files.\n+ * Conservative: includes every `case \"X\":`, `.command(\"X\")`, and `| \"X\"` in\n+ * the CommandName union. Over-approximation is safe — it means we might fail\n+ * to flag a nonexistent command, but #1532's registrar will tighten this.\n+ *\n+ * @param {string[]} cliFiles — repo-relative posix paths\n+ * @returns {Set}\n+ */\n+function collectRegisteredCommands(cliFiles) {\n+ const commands = new Set();\n+ for (const rel of cliFiles) {\n+ const abs = path.join(ROOT, ...rel.split(\"/\"));\n+ if (!existsSync(abs)) continue;\n+ const src = readFileSync(abs, \"utf8\");\n+ let m;\n+ CASE_COMMAND_RE.lastIndex = 0;\n+ while ((m = CASE_COMMAND_RE.exec(src)) !== null) {\n+ commands.add(m[1]);\n+ }\n+ COMMANDER_COMMAND_RE.lastIndex = 0;\n+ while ((m = COMMANDER_COMMAND_RE.exec(src)) !== null) {\n+ commands.add(m[1]);\n+ }\n+ COMMAND_NAME_UNION_RE.lastIndex = 0;\n+ while ((m = COMMAND_NAME_UNION_RE.exec(src)) !== null) {\n+ commands.add(m[1]);\n+ }\n+ }\n+ return commands;\n+}\n+\n+// ── No-op handler detection ────────────────────────────────────────────────\n+\n+/**\n+ * Scan CLI source for no-op handler markers and return the set of\n+ * \"command path\" strings (e.g. \"extensions reload\") whose handler contains a\n+ * no-op label.\n+ *\n+ * Two CLI styles are handled:\n+ * - remnic-cli/src/index.ts — `async function cmd(...)` enclosing a\n+ * `switch` with `case \"Y\":` arms. The no-op path is ` `.\n+ * When no function context is found, falls back to the bare case label.\n+ * - remnic-core/src/cli.ts — commander `.command(\"parent\")` chained with\n+ * `.command(\"child\")`. The path is the chain joined with spaces.\n+ *\n+ * The detection is intentionally conservative: it only flags handlers that\n+ * explicitly label themselves as no-ops (`No-op stub`, `no-op:`,\n+ * `not yet implemented`). A genuinely empty handler without a marker is\n+ * invisible to static analysis and is caught at review time.\n+ *\n+ * @param {string[]} cliFiles\n+ * @returns {Set} detected no-op command paths\n+ */\n+function detectNoOpHandlers(cliFiles) {\n+ const detected = new Set();\n+\n+ const FUNC_RE = /(?:async\\s+)?function\\s+cmd([A-Z][A-Za-z0-9]*)\\s*\\(/;\n+ const CASE_RE = /^\\s*case\\s+\"([A-Za-z][A-Za-z0-9:_-]*)\"\\s*:/;\n+ const COMMANDER_RE = /\\.\\s*command\\(\\s*\"([A-Za-z][A-Za-z0-9:_-]*)\"\\s*\\)/;\n+\n+ /** Convert a PascalCase function-name suffix to the CLI command name\n+ * (e.g. `Extensions` → `extensions`, `ConnectorsMarketplace` →\n+ * `connectors-marketplace`). */\n+ function pascalToKebab(p) {\n+ return p\n+ .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n+ .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1-$2\")\n+ .toLowerCase();\n+ }\n+\n+ for (const rel of cliFiles) {\n+ const abs = path.join(ROOT, ...rel.split(\"/\"));\n+ if (!existsSync(abs)) continue;\n+ const src = readFileSync(abs, \"utf8\");\n+ const lines = src.split(\"\\n\");\n+\n+ // ── Pass 1: function-scoped case dispatch (remnic-cli style) ──────\n+ let funcName = null; // current cmd suffix, e.g. \"Extensions\"\n+ let funcKebab = null; // kebab form, e.g. \"extensions\"\n+ let currentCase = null;\n+\n+ for (let i = 0; i < lines.length; i++) {\n+ const line = lines[i];\n+\n+ // Function entry — remember the cmd suffix for path building.\n+ const funcMatch = line.match(FUNC_RE);\n+ if (funcMatch) {\n+ funcName = funcMatch[1];\n+ funcKebab = pascalToKebab(funcName);\n+ currentCase = null;\n+ }\n+\n+ // Case label inside the function's switch.\n+ const caseMatch = line.match(CASE_RE);\n+ if (caseMatch) {\n+ currentCase = caseMatch[1];\n+ }\n+\n+ // No-op marker — attribute to the current scope.\n+ if (NO_OP_MARKER_RE.test(line)) {\n+ if (funcKebab && currentCase) {\n+ detected.add(`${funcKebab} ${currentCase}`);\n+ } else if (currentCase) {\n+ detected.add(currentCase);\n+ }\n+ }\n+ }\n+\n+ // ── Pass 2: commander-style `.command(\"X\")` chains (cli.ts style) ─\n+ const cmdChain = [];\n+ for (let i = 0; i < lines.length; i++) {\n+ const line = lines[i];\n+ const cmdMatch = line.match(COMMANDER_RE);\n+ if (cmdMatch) {\n+ const name = cmdMatch[1];\n+ // Sibling commands pop the chain: a new .command() on the same\n+ // object replaces the leaf. We keep the chain at length <= 2\n+ // (parent + child), matching every use in cli.ts.\n+ if (cmdChain.length >= 2) cmdChain.pop();\n+ cmdChain.push(name);\n+ continue;\n+ }\n+ if (NO_OP_MARKER_RE.test(line) && cmdChain.length > 0) {\n+ detected.add(cmdChain.join(\" \"));\n+ }\n+ }\n+ }\n+ return detected;\n+}\n+\n+// ── Stub-publisher capability scan ─────────────────────────────────────────\n+\n+const PUBLISHERS = [\n+ \"packages/remnic-core/src/memory-extension/claude-code-publisher.ts\",\n+ \"packages/remnic-core/src/memory-extension/codex-publisher.ts\",\n+ \"packages/remnic-core/src/memory-extension/hermes-publisher.ts\",\n+];\n+\n+const CAPABILITIES_FALSE_RE = /static\\s+readonly\\s+capabilities\\s*:[\\s\\S]*?instructionsMd:\\s*false[\\s\\S]*?skillsFolder:\\s*false[\\s\\S]*?citationFormat:\\s*false[\\s\\S]*?readPathTemplate:\\s*false/s;\n+const HOST_ID_RE = /readonly\\s+hostId\\s*=\\s*\"([^\"]+)\"/;\n+\n+/**\n+ * @returns {Map}\n+ */\n+function collectPublishers() {\n+ const out = new Map();\n+ for (const rel of PUBLISHERS) {\n+ const abs = path.join(ROOT, ...rel.split(\"/\"));\n+ if (!existsSync(abs)) continue;\n+ const src = readFileSync(abs, \"utf8\");\n+ const hostMatch = src.match(HOST_ID_RE);\n+ if (!hostMatch) continue;\n+ const hostId = hostMatch[1];\n+ // A publisher is a stub when ALL four capability flags are false. We\n+ // require the full all-false literal block so a partial publisher (some\n+ // true, some false) is not mis-flagged.\n+ const allFalse = CAPABILITIES_FALSE_RE.test(src);\n+ out.set(hostId, { hostId, isStub: allFalse, file: rel });\n+ }\n+ return out;\n+}\n+\n+// ── Install-section automation-phrase scan ─────────────────────────────────\n+\n+/**\n+ * Extract the concatenated text of install sections from a markdown source.\n+ * Sections are identified by INSTALL_HEADING_RE; the section extends from the\n+ * heading to the next heading of the same or higher level (or EOF).\n+ *\n+ * @param {string} src\n+ * @returns {Array<{ heading: string; text: string; startLine: number }>}\n+ */\n+function extractInstallSections(src) {\n+ const lines = src.split(\"\\n\");\n+ const sections = [];\n+ for (let i = 0; i < lines.length; i++) {\n+ if (!INSTALL_HEADING_RE.test(lines[i])) continue;\n+ const headingMatch = lines[i].match(/^(#{1,6})/);\n+ const level = headingMatch ? headingMatch[1].length : 1;\n+ const heading = lines[i];\n+ const startLine = i + 1;\n+ const bodyLines = [];\n+ i++;\n+ while (i < lines.length) {\n+ const nextHeading = lines[i].match(/^(#{1,6})\\s/);\n+ if (nextHeading && nextHeading[1].length <= level) break;\n+ bodyLines.push(lines[i]);\n+ i++;\n+ }\n+ sections.push({ heading, text: bodyLines.join(\"\\n\"), startLine });\n+ i--; // compensate for outer loop's i++\n+ }\n+ return sections;\n+}\n+\n+function findAutomationPhases(text) {\n+ const lower = text.toLowerCase();\n+ const hits = [];\n+ for (const phrase of STUB_AUTOMATION_PHRASES) {\n+ let idx = lower.indexOf(phrase);\n+ while (idx !== -1) {\n+ hits.push({ phrase, idx });\n+ idx = lower.indexOf(phrase, idx + 1);\n+ }\n+ }\n+ return hits;\n+}\n+\n+// ── Main ───────────────────────────────────────────────────────────────────\n+\n+function usage() {\n+ return [\n+ \"Usage: node scripts/check-docs-parity.mjs [--help]\",\n+ \"\",\n+ \" Static docs-code parity check (#1527 PR2). Verifies every\",\n+ \" `remnic ` in docs fenced code blocks resolves to a\",\n+ \" registered CLI command; gates automation claims in stub-publisher\",\n+ \" install docs; rejects unlisted no-op commands. No flags beyond --help.\",\n+ \"\",\n+ \" REMNIC_DOCS_PARITY_ROOT — test seam (absolute path to fake repo root).\",\n+ ].join(\"\\n\");\n+}\n+\n+function fail(failures) {\n+ console.error(\"[docs-parity] drift detected — docs and CLI are out of sync (#1527):\");\n+ for (const f of failures) {\n+ console.error(`[docs-parity] - ${f}`);\n+ }\n+ console.error(\n+ \"[docs-parity] fix the docs, the CLI, or — for a deliberate no-op — add to NO_OP_ALLOWLIST with a tracking issue.\",\n+ );\n+ process.exit(1);\n+}\n+\n+function main() {\n+ const args = process.argv.slice(2);\n+ const unknown = args.filter((a) => a !== \"--help\");\n+ if (unknown.length > 0) {\n+ console.error(`[docs-parity] ERROR: unknown argument(s): ${unknown.join(\", \")}`);\n+ console.error(usage());\n+ process.exit(2);\n+ }\n+ if (args.includes(\"--help\")) {\n+ console.log(usage());\n+ return;\n+ }\n+\n+ const failures = [];\n+\n+ // (a) Command existence.\n+ const registered = collectRegisteredCommands(CLI_FILES);\n+ if (registered.size === 0) {\n+ fail([\n+ \"no registered commands found — CLI_FILES resolved to nothing. \" +\n+ \"Check that packages/remnic-cli/src/index.ts and packages/remnic-core/src/cli.ts exist under the scan root.\",\n+ ]);\n+ }\n+\n+ const docFiles = collectDocFiles();\n+ /** @type {Map>} */\n+ const documented = new Map();\n+ for (const rel of docFiles) {\n+ const abs = path.join(ROOT, ...rel.split(\"/\"));\n+ const src = readFileSync(abs, \"utf8\");\n+ const invocations = extractRemnicInvocations(rel, src);\n+ for (const inv of invocations) {\n+ const list = documented.get(inv.subcommand) ?? [];\n+ list.push(inv);\n+ documented.set(inv.subcommand, list);\n+ }\n+ }\n+\n+ for (const [subcommand, occs] of documented) {\n+ if (registered.has(subcommand)) continue;\n+ const first = occs[0];\n+ failures.push(\n+ `documented command \"remnic ${subcommand}\" is not registered in the CLI ` +\n+ `(first occurrence: ${first.file}:${first.line}: \\`${first.full}\\`)`,\n+ );\n+ }\n+\n+ // (c) No-op allowlist. Detect no-op handlers in the CLI, then require every\n+ // detected no-op to be in NO_OP_ALLOWLIST with a non-empty tracking issue.\n+ const detectedNoOps = detectNoOpHandlers(CLI_FILES);\n+ for (const cmd of detectedNoOps) {\n+ if (!(cmd in NO_OP_ALLOWLIST)) {\n+ failures.push(\n+ `no-op handler \"${cmd}\" is not in NO_OP_ALLOWLIST — ` +\n+ \"add it with a tracking-issue number, or implement the handler\",\n+ );\n+ }\n+ }\n+ for (const [cmd, issue] of Object.entries(NO_OP_ALLOWLIST)) {\n+ if (!issue || !issue.trim()) {\n+ failures.push(\n+ `NO_OP_ALLOWLIST entry \"${cmd}\" is missing a tracking-issue reference`,\n+ );\n+ }\n+ }\n+\n+ // (b) Stub-honesty. For each stub publisher, scan its mapped docs' install\n+ // sections for automation phrases.\n+ const publishers = collectPublishers();\n+ for (const [hostId, info] of publishers) {\n+ if (!info.isStub) continue;\n+ const docs = STUB_PUBLISHER_DOCS[hostId] ?? [];\n+ for (const rel of docs) {\n+ const abs = path.join(ROOT, ...rel.split(\"/\"));\n+ if (!existsSync(abs)) continue;\n+ const src = readFileSync(abs, \"utf8\");\n+ const sections = extractInstallSections(src);\n+ for (const section of sections) {\n+ const hits = findAutomationPhases(section.text);\n+ for (const hit of hits) {\n+ failures.push(\n+ `stub publisher \"${hostId}\" doc ${rel} (section \"${section.heading.trim()}\") ` +\n+ `contains automation phrase \"${hit.phrase}\" — the publisher declares no capabilities`,\n+ );\n+ }\n+ }\n+ }\n+ }\n+\n+ if (failures.length > 0) {\n+ fail(failures);\n+ }\n+\n+ // Summary for green runs.\n+ const docCommands = [...documented.keys()].sort();\n+ console.log(\n+ `[docs-parity] OK — ${docCommands.length} documented command(s) resolve; ` +\n+ `${detectedNoOps.size} no-op(s) tracked; ` +\n+ `${[...publishers.values()].filter((p) => p.isStub).length} stub publisher(s) honest.`,\n+ );\n+ if (docCommands.length > 0) {\n+ console.log(`[docs-parity] commands: ${docCommands.join(\", \")}`);\n+ }\n+}\n+\n+main();", "status": "added"}, {"additions": 1, "deletions": 0, "filename": "scripts/pr-preflight.sh", "patch": "@@ -54,6 +54,7 @@ run npm run check-config-contract\n run npm run plugin:inspect\n run bash scripts/check-review-patterns.sh\n run node scripts/check-ratchets.mjs\n+run node scripts/check-docs-parity.mjs\n run pnpm exec turbo --version\n run_quiet pnpm exec turbo run check-types --dry=json\n ", "status": "modified"}, {"additions": 418, "deletions": 0, "filename": "tests/check-docs-parity.test.mjs", "patch": "@@ -0,0 +1,418 @@\n+// Docs-code parity check tests (issue #1527 PR2).\n+//\n+// Mirrors check-ratchets.test.mjs conventions: spawnSync the script with a\n+// REMNIC_DOCS_PARITY_ROOT pointing at a synthetic fixture repo, assert exit\n+// codes + stderr/stdout. Each gate has a prove-fail-before case: seed a\n+// violation, show the script fails, then show the fix passes.\n+\n+import assert from \"node:assert/strict\";\n+import { spawnSync } from \"node:child_process\";\n+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import path from \"node:path\";\n+import { test } from \"node:test\";\n+import { fileURLToPath } from \"node:url\";\n+\n+const SCRIPT = path.join(\n+ path.dirname(fileURLToPath(import.meta.url)),\n+ \"..\",\n+ \"scripts\",\n+ \"check-docs-parity.mjs\",\n+);\n+\n+function runParity(root) {\n+ return spawnSync(process.execPath, [SCRIPT], {\n+ encoding: \"utf8\",\n+ env: {\n+ ...process.env,\n+ REMNIC_DOCS_PARITY_ROOT: root,\n+ },\n+ });\n+}\n+\n+/**\n+ * Build a minimal fixture repo root. Every gate's fixture starts from this\n+ * base so the \"green\" pieces (registered commands, honest stub publishers)\n+ * are always present; each test then adds the specific violation it wants to\n+ * exercise.\n+ */\n+function makeBaseFixture() {\n+ const root = mkdtempSync(path.join(tmpdir(), \"docs-parity-test-\"));\n+\n+ // CLI: two files. remnic-cli has a case-based dispatch; cli.ts has\n+ // commander-style registrations. Together they exercise both registration\n+ // scanners.\n+ const cliDir = path.join(root, \"packages\", \"remnic-cli\", \"src\");\n+ mkdirSync(cliDir, { recursive: true });\n+ writeFileSync(\n+ path.join(cliDir, \"index.ts\"),\n+ [\n+ 'type CommandName = \"init\" | \"status\" | \"extensions\" | \"daemon\";',\n+ \"\",\n+ \"async function cmdExtensions(action: string, rest: string[]) {\",\n+ \" switch (action) {\",\n+ ' case \"list\":',\n+ ' console.log(\"list\");',\n+ \" break;\",\n+ ' case \"reload\": {',\n+ \" // No-op stub reserved for future caching\",\n+ ' console.log(\"Extension cache reloaded (no-op: caching not yet implemented).\");',\n+ \" break;\",\n+ \" }\",\n+ \" default:\",\n+ \" break;\",\n+ \" }\",\n+ \"}\",\n+ \"\",\n+ \"async function main() {\",\n+ \" const [command, ...rest] = process.argv.slice(2);\",\n+ \" switch (command as CommandName) {\",\n+ ' case \"init\":',\n+ \" break;\",\n+ ' case \"extensions\":',\n+ \" await cmdExtensions(rest[0], rest.slice(1));\",\n+ \" break;\",\n+ \" default:\",\n+ \" break;\",\n+ \" }\",\n+ \"}\",\n+ \"\",\n+ \"main();\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const coreCliDir = path.join(root, \"packages\", \"remnic-core\", \"src\");\n+ mkdirSync(coreCliDir, { recursive: true });\n+ writeFileSync(\n+ path.join(coreCliDir, \"cli.ts\"),\n+ [\n+ 'const cmd = program.command(\"engram\");',\n+ 'cmd.command(\"doctor\").description(\"Run diagnostics\").action(async () => {});',\n+ 'cmd.command(\"recall\").description(\"Run recall\").action(async () => {});',\n+ 'cmd.command(\"tier\").description(\"Tier ops\").action(async () => {});',\n+ ].join(\"\\n\"),\n+ );\n+\n+ // Stub publisher (claude-code): all-false capabilities.\n+ const pubDir = path.join(root, \"packages\", \"remnic-core\", \"src\", \"memory-extension\");\n+ mkdirSync(pubDir, { recursive: true });\n+ // Stub publisher (claude-code): all-false capabilities.\n+ writeFileSync(\n+ path.join(pubDir, \"claude-code-publisher.ts\"),\n+ [\n+ \"interface PublisherCapabilities {}\",\n+ 'export class ClaudeCodeMemoryExtensionPublisher {',\n+ ' readonly hostId = \"claude-code\";',\n+ \" static readonly capabilities: PublisherCapabilities = {\",\n+ \" instructionsMd: false,\",\n+ \" skillsFolder: false,\",\n+ \" citationFormat: false,\",\n+ \" readPathTemplate: false,\",\n+ \" };\",\n+ \"}\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ // Real publisher (codex): some-true capabilities — not gated.\n+ writeFileSync(\n+ path.join(pubDir, \"codex-publisher.ts\"),\n+ [\n+ \"interface PublisherCapabilities {}\",\n+ 'export class CodexMemoryExtensionPublisher {',\n+ ' readonly hostId = \"codex\";',\n+ \" static readonly capabilities: PublisherCapabilities = {\",\n+ \" instructionsMd: true,\",\n+ \" skillsFolder: false,\",\n+ \" citationFormat: true,\",\n+ \" readPathTemplate: true,\",\n+ \" };\",\n+ \"}\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ // Honest stub-publisher doc (no automation claims in install section).\n+ const pluginDocsDir = path.join(root, \"docs\", \"plugins\");\n+ mkdirSync(pluginDocsDir, { recursive: true });\n+ writeFileSync(\n+ path.join(pluginDocsDir, \"claude-code.md\"),\n+ [\n+ \"# Claude Code Plugin\",\n+ \"\",\n+ \"## Install\",\n+ \"\",\n+ \"Three manual steps. The publisher is a stub — nothing is written for you.\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic init\",\n+ \"```\",\n+ \"\",\n+ \"## Runtime\",\n+ \"\",\n+ \"Once set up, memory works in Claude Code sessions.\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ // A doc with a registered fenced invocation (green path).\n+ const docsDir = path.join(root, \"docs\");\n+ writeFileSync(\n+ path.join(docsDir, \"guide.md\"),\n+ [\n+ \"# Guide\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic status\",\n+ \"remnic doctor\",\n+ \"remnic extensions list\",\n+ \"```\",\n+ \"\",\n+ \"Prose mention of remnic recall should not be checked (outside a fence).\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ // Package README with a registered fenced invocation.\n+ const pkgDir = path.join(root, \"packages\", \"plugin-claude-code\");\n+ mkdirSync(pkgDir, { recursive: true });\n+ writeFileSync(\n+ path.join(pkgDir, \"README.md\"),\n+ [\n+ \"# plugin-claude-code\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic init\",\n+ \"```\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ return root;\n+}\n+\n+function withFixture(fn) {\n+ const root = makeBaseFixture();\n+ try {\n+ fn(root);\n+ } finally {\n+ rmSync(root, { recursive: true, force: true });\n+ }\n+}\n+\n+// ── Green path ─────────────────────────────────────────────────────────────\n+\n+test(\"base fixture passes — all commands resolve, stub is honest, no-op tracked\", () => {\n+ withFixture((root) => {\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ assert.match(result.stdout, /\\[docs-parity\\] OK/);\n+ assert.match(result.stdout, /4 documented command\\(s\\) resolve/);\n+ assert.match(result.stdout, /1 no-op\\(s\\) tracked/);\n+ assert.match(result.stdout, /1 stub publisher\\(s\\) honest/);\n+ });\n+});\n+\n+// ── Gate (a): nonexistent documented command ───────────────────────────────\n+test(\"a documented command that is not registered fails the check\", () => {\n+ withFixture((root) => {\n+ writeFileSync(\n+ path.join(root, \"docs\", \"bogus.md\"),\n+ [\n+ \"# Bogus\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic nonexistent-command --flag\",\n+ \"```\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 1);\n+ assert.match(result.stderr, /documented command \"remnic nonexistent-command\" is not registered/);\n+ assert.match(result.stderr, /bogus\\.md/);\n+ });\n+});\n+\n+test(\"prose mention of a bogus command outside a fenced block does NOT fail\", () => {\n+ withFixture((root) => {\n+ writeFileSync(\n+ path.join(root, \"docs\", \"prose.md\"),\n+ [\n+ \"# Prose\",\n+ \"\",\n+ \"You could try `remnic totally-bogus` but it does not exist.\",\n+ \"\",\n+ \" remnic indented-but-not-fenced\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ });\n+});\n+\n+// ── Gate (b): automation claim for stub publisher ──────────────────────────\n+\n+test(\"an automation phrase in a stub publisher's install section fails\", () => {\n+ withFixture((root) => {\n+ writeFileSync(\n+ path.join(root, \"docs\", \"plugins\", \"claude-code.md\"),\n+ [\n+ \"# Claude Code Plugin\",\n+ \"\",\n+ \"## Install\",\n+ \"\",\n+ \"The installer automatically configures everything for you.\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic init\",\n+ \"```\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 1);\n+ assert.match(result.stderr, /stub publisher \"claude-code\"/);\n+ assert.match(result.stderr, /automation phrase \"automatically\"/);\n+ });\n+});\n+\n+test(\"an automation phrase outside the install section does NOT fail\", () => {\n+ withFixture((root) => {\n+ writeFileSync(\n+ path.join(root, \"docs\", \"plugins\", \"claude-code.md\"),\n+ [\n+ \"# Claude Code Plugin\",\n+ \"\",\n+ \"## Install\",\n+ \"\",\n+ \"Manual only. The publisher is a stub.\",\n+ \"\",\n+ \"## Runtime\",\n+ \"\",\n+ \"Once installed, the daemon automatically recalls context.\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ });\n+});\n+\n+test(\"a real publisher (some-true capabilities) is NOT gated\", () => {\n+ withFixture((root) => {\n+ // Codex has instructionsMd: true — it may claim automation.\n+ writeFileSync(\n+ path.join(root, \"docs\", \"plugins\", \"codex.md\"),\n+ [\n+ \"# Codex Plugin\",\n+ \"\",\n+ \"## Install\",\n+ \"\",\n+ \"The installer automatically writes instructions.md and configures MCP.\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic init\",\n+ \"```\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ });\n+});\n+\n+// ── Gate (c): unlisted no-op ───────────────────────────────────────────────\n+\n+test(\"a no-op handler not in the allowlist fails the check\", () => {\n+ withFixture((root) => {\n+ // Add a new no-op handler to the CLI that is NOT in NO_OP_ALLOWLIST.\n+ const cliPath = path.join(root, \"packages\", \"remnic-cli\", \"src\", \"index.ts\");\n+ const original = `async function main() {`;\n+ const withExtra = `async function cmdSync(action: string) {\\n switch (action) {\\n case \"watch\":\\n // No-op stub: not yet implemented\\n break;\\n default:\\n break;\\n }\\n}\\n\\n${original}`;\n+ let src = readFileSyncSafe(cliPath);\n+ src = src.replace(original, withExtra);\n+ writeFileSync(cliPath, src);\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 1);\n+ assert.match(result.stderr, /no-op handler \"sync watch\" is not in NO_OP_ALLOWLIST/);\n+ });\n+});\n+\n+test(\"a no-op handler that IS in the allowlist passes\", () => {\n+ withFixture((root) => {\n+ // The base fixture already has \"extensions reload\" as a no-op, and the\n+ // script seeds it in NO_OP_ALLOWLIST. Verify it passes.\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ assert.match(result.stdout, /1 no-op\\(s\\) tracked/);\n+ });\n+});\n+\n+// ── Command discovery from both CLI files ──────────────────────────────────\n+\n+test(\"commands registered in remnic-core/src/cli.ts via .command() are recognized\", () => {\n+ withFixture((root) => {\n+ // \"doctor\", \"recall\", \"tier\" come from cli.ts. Add them to a doc.\n+ writeFileSync(\n+ path.join(root, \"docs\", \"core-commands.md\"),\n+ [\n+ \"# Core Commands\",\n+ \"\",\n+ \"```bash\",\n+ \"remnic recall\",\n+ \"remnic tier\",\n+ \"```\",\n+ \"\",\n+ ].join(\"\\n\"),\n+ );\n+\n+ const result = runParity(root);\n+ assert.equal(result.status, 0, result.stderr);\n+ });\n+});\n+\n+// ── Misc ────────────────────────────────────────────────────────────────────\n+\n+test(\"unknown arguments are rejected with usage\", () => {\n+ withFixture((root) => {\n+ const result = spawnSync(\n+ process.execPath,\n+ [SCRIPT, \"--bogus\"],\n+ {\n+ encoding: \"utf8\",\n+ env: { ...process.env, REMNIC_DOCS_PARITY_ROOT: root },\n+ },\n+ );\n+ assert.equal(result.status, 2);\n+ assert.match(result.stderr, /unknown argument/);\n+ assert.match(result.stderr, /--help/);\n+ });\n+});\n+\n+test(\"--help prints usage and exits 0\", () => {\n+ withFixture((root) => {\n+ const result = spawnSync(\n+ process.execPath,\n+ [SCRIPT, \"--help\"],\n+ {\n+ encoding: \"utf8\",\n+ env: { ...process.env, REMNIC_DOCS_PARITY_ROOT: root },\n+ },\n+ );\n+ assert.equal(result.status, 0);\n+ assert.match(result.stdout, /docs-code parity check/);\n+ assert.match(result.stdout, /REMNIC_DOCS_PARITY_ROOT/);\n+ });\n+});\n+\n+// ── Helpers ─────────────────────────────────────────────────────────────────\n+\n+function readFileSyncSafe(p) {\n+ return readFileSync(p, \"utf8\");\n+}", "status": "added"}], "message": "docs: docs-code parity check (#1527 PR2)\n\nStatic docs-code parity check (scripts/check-docs-parity.mjs). Three gates,\nall pure static analysis (no daemon, no network — CI runs it cold):\n\n(a) Command existence — every 'remnic ' invocation extracted\n from fenced code blocks in docs/ + packages/*/README.md must resolve to\n a command registered in the CLI. Registration is discovered by grepping\n packages/remnic-cli/src/index.ts (CommandName union + case dispatch) and\n packages/remnic-core/src/cli.ts (.command() calls). TODO_REGISTRY marker\n references #1532's future registrar table.\n\n(b) Stub-honesty — a memory-extension publisher whose PublisherCapabilities\n are all-false may not have install-section docs containing automation\n phrases ('installs the plugin', 'configures MCP', 'automatically').\n Host-to-doc mapping maintained in the script.\n\n(c) No-op allowlist — a CLI handler labelled as a no-op stub must be listed\n in NO_OP_ALLOWLIST with a tracking-issue number. Seed: 'extensions reload'\n -> #1518.\n\nTests (tests/check-docs-parity.test.mjs) prove-fail-before each gate: seed a\nviolation in a fixture, show the script fails, then show the fix passes. 11\ntests, all green.\n\nWired into scripts/pr-preflight.sh (after check-ratchets) and the CI quality\njob (.github/workflows/ci.yml). npm script: check:docs-parity.\n\nCurrent docs tree passes: 40 documented commands resolve, 1 no-op tracked,\n2 stub publishers honest.\n\nPart of #1520. Refs #1527, #1518, #1532.\n\nChokepoints used: N/A (docs-only static analysis; no orchestrator/storage/\nconfig/caps changes).", "sha": "ff5f6283d07020f26d2fa173174943ed974b64a7"}], "post_review_commits": ["d5a4945f7ccd8049549057223bb467758d1078f0", "235c76604c12a82ff1b512697ebd618f825a2801", "eac125c93effcd9aa47cdfe69f2ddaceb76ff70c", "a168272659faf23b41972d0818336796ca1ce6c5", "0e1e25038a2b757016f76c92f63e2b95e6122170", "2adfb7c767c90c0a5374afb64ef7b26d3f63455f", "fa7780ca022c84bc27fec6e4d89194239020436a", "59171a60068dee389b9ef0854c43d560c230368c", "9d30f4e2b4d09882fc264e2f9b29df06cc189fd6", "8370712fb518f8edad070c51c55e2561502f40be"], "pr_author": "joshuaswarren", "pr_title": "docs: docs-code parity check (#1527 PR2)", "repo_name": "joshuaswarren/remnic"}, "repo": "joshuaswarren/remnic", "snapshot": "snapshots/04cbaab65c329486ed65457e97ddd39bbd0186c7835ff73d983a8e8eb06b43d8.pack", "split": "eval", "task_id": "260e87a49d54603065307811d6a5694ebb093499b0e3bf93160eda69ff5105a1"} {"base_sha": "fc8a19c4f555189c4b4fa7bccf2cf454936b1901", "cohort": "scored_zero", "context": {"canonical_pr_url": "https://github.com/yippee0903/Upload-Assistant/pull/273", "id": "2633420d509a201e91e09ee10c0e47094f4e62984b5e716f6a44691679eb12a2", "preparation_mode": "source-only", "snapshot": {"base_ref": "fc8a19c4f555189c4b4fa7bccf2cf454936b1901", "base_sha": "fc8a19c4f555189c4b4fa7bccf2cf454936b1901", "body": "", "head_ref": "694128384aba2e96cc4461cdf0e1a6dd9955786b", "head_sha": "694128384aba2e96cc4461cdf0e1a6dd9955786b", "name": "Upload-Assistant", "number": 273, "owner": "yippee0903", "pr_url": "https://github.com/yippee0903/Upload-Assistant/pull/273", "title": ""}}, "head_sha": "694128384aba2e96cc4461cdf0e1a6dd9955786b", "metadata": {"group_id": "041c0f37d16e21563659000d374881a6c10b58c328512084b1367565701a5e2b", "snapshot": {"base_sha": "fc8a19c4f555189c4b4fa7bccf2cf454936b1901", "external_requirements": [], "head_sha": "694128384aba2e96cc4461cdf0e1a6dd9955786b", "objects": 272, "objects_sha256": "7050d56342f6938e89c964fe315f0e50a9513d99b48ddbd877220e4f8b4ecfb7", "patch_sha256": "017d5256000127865d0a524978d340aaf26da7b88c151ea2c8f04be548c1b7c0"}}, "pr_number": 273, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "a310b86278b0", "description": "The rename check matched the shorter `.ts` suffix before `.m2ts`, stripping only `.ts` and leaving `.m2`. This falsely classified unchanged `.m2ts` filenames as renamed and could block uploads.", "file_path": "src/trackers/COMMON.py"}], "commits_under_review": [{"author": "yippee0903", "date": "2026-06-28T10:43:14Z", "files": [{"additions": 56, "deletions": 8, "filename": "src/trackers/COMMON.py", "patch": "@@ -3078,7 +3078,7 @@ async def check_detag(self, meta: dict[str, Any], tracker: str) -> bool:\n torrent_tag = meta.get(\"tag\", \"\")\n torrent_group = torrent_tag.lstrip(\"-\").strip() if torrent_tag else \"\"\n \n- mi_filename = await self._get_mediainfo_filename(meta)\n+ mi_filename, disk_filename = await self._get_mediainfo_filename(meta)\n mi_group = self._extract_group_from_filename(mi_filename) if mi_filename else \"\"\n \n if not torrent_group:\n@@ -3098,25 +3098,47 @@ async def check_detag(self, meta: dict[str, Any], tracker: str) -> bool:\n }\n return True\n \n+ # Rename: the embedded name is a real release name (it carries a group\n+ # tag, so we trust its format) but the on-disk filename no longer matches\n+ # it. Renamed files are always refused — they usually hide a faked\n+ # quality/source and need manual verification.\n+ if mi_filename and mi_group and disk_filename and self._is_renamed(disk_filename, mi_filename):\n+ meta[\"detag_info\"] = {\n+ \"type\": \"rename\",\n+ \"torrent_group\": torrent_group,\n+ \"mi_group\": mi_group,\n+ \"mi_filename\": mi_filename,\n+ \"disk_filename\": disk_filename,\n+ }\n+ return True\n+\n return False\n \n- async def _get_mediainfo_filename(self, meta: dict[str, Any]) -> str:\n- \"\"\"Read the original release name from MEDIAINFO_CLEANPATH.txt.\"\"\"\n+ async def _get_mediainfo_filename(self, meta: dict[str, Any]) -> tuple[str, str]:\n+ \"\"\"Read the embedded release name and the on-disk filename from\n+ MEDIAINFO_CLEANPATH.txt.\n+\n+ Returns ``(embedded_name, disk_name)`` where *embedded_name* is the\n+ ``Movie name``/``Title`` the release group muxed into the container and\n+ *disk_name* is ``Complete name`` (rewritten to the current basename by\n+ exportmi). A mismatch between the two means the file was renamed.\n+ \"\"\"\n base_dir = meta.get(\"base_dir\", \".\")\n uuid = meta.get(\"uuid\", \"\")\n if not uuid:\n- return \"\"\n+ return \"\", \"\"\n \n cleanpath = os.path.join(base_dir, \"tmp\", uuid, \"MEDIAINFO_CLEANPATH.txt\")\n if not os.path.isfile(cleanpath):\n- return \"\"\n+ return \"\", \"\"\n \n try:\n async with aiofiles.open(cleanpath, encoding=\"utf-8\", errors=\"ignore\") as f:\n content = await f.read()\n \n movie_name = \"\"\n title = \"\"\n+ complete_name = \"\"\n in_general = False\n for line in content.splitlines():\n stripped = line.strip()\n@@ -3126,7 +3148,11 @@ async def _get_mediainfo_filename(self, meta: dict[str, Any]) -> str:\n if in_general and stripped == \"\":\n break\n if in_general:\n- if stripped.startswith(\"Movie name\"):\n+ if stripped.startswith(\"Complete name\"):\n+ parts = line.split(\":\", 1)\n+ if len(parts) == 2:\n+ complete_name = parts[1].strip()\n+ elif stripped.startswith(\"Movie name\"):\n parts = line.split(\":\", 1)\n if len(parts) == 2:\n movie_name = parts[1].strip()\n@@ -3135,11 +3161,33 @@ async def _get_mediainfo_filename(self, meta: dict[str, Any]) -> str:\n if len(parts) == 2:\n title = parts[1].strip()\n \n- return movie_name or title\n+ return movie_name or title, complete_name\n except OSError:\n pass\n \n- return \"\"\n+ return \"\", \"\"\n+\n+ @staticmethod\n+ def _is_renamed(disk_name: str, embedded_name: str) -> bool:\n+ \"\"\"True when the on-disk filename differs from the name the release group\n+ muxed into the container.\n+\n+ The comparison is exact — only a trailing media extension is dropped\n+ (the embedded name usually carries none). Even a dot-vs-space difference\n+ counts as a rename, because cross-seeding needs byte-identical filenames,\n+ so any change to the name is rejected.\n+ \"\"\"\n+ known_ext = (\".mkv\", \".mp4\", \".avi\", \".ts\", \".m2ts\", \".wmv\", \".mpg\", \".mpeg\", \".vob\", \".iso\")\n+\n+ def strip_ext(s: str) -> str:\n+ for ext in known_ext:\n+ if s.lower().endswith(ext):\n+ return s[: -len(ext)]\n+ return s\n+\n+ disk = strip_ext(disk_name).strip()\n+ embedded = strip_ext(embedded_name).strip()\n+ return bool(disk) and bool(embedded) and disk != embedded\n \n @staticmethod\n def _extract_group_from_filename(filename: str) -> str:", "status": "modified"}, {"additions": 57, "deletions": 0, "filename": "tests/test_common.py", "patch": "@@ -155,3 +155,60 @@ def test_mixed_list_with_non_strings(self, common):\n meta, \"TEST\", languages_to_check=[\"french\"], check_audio=True\n ))\n assert result is True\n+\n+\n+# ═══════════════════════════════════════════════════════════════\n+# _is_renamed() and check_detag() rename detection\n+# ═══════════════════════════════════════════════════════════════\n+\n+\n+class TestRenameDetection:\n+ \"\"\"The on-disk filename must match the name muxed in by the release group.\"\"\"\n+\n+ @pytest.fixture\n+ def common(self):\n+ return COMMON(config=_config())\n+\n+ def test_not_renamed_extension_only(self, common):\n+ # On-disk name == embedded name apart from the extension → not renamed.\n+ assert common._is_renamed(\"Movie.2026.1080p.BluRay.x264-GRP.mkv\", \"Movie.2026.1080p.BluRay.x264-GRP\") is False\n+\n+ def test_renamed_dots_vs_spaces(self, common):\n+ # Even a separator change breaks cross-seeding → treated as a rename.\n+ assert common._is_renamed(\"Movie 2026 1080p BluRay x264-GRP.mkv\", \"Movie.2026.1080p.BluRay.x264-GRP\") is True\n+\n+ def test_not_renamed_exact_match(self, common):\n+ # Identical apart from the extension → not renamed.\n+ assert common._is_renamed(\"Movie.2026.1080p.BluRay.x264-GRP.mkv\", \"Movie.2026.1080p.BluRay.x264-GRP\") is False\n+\n+ def test_renamed_to_junk(self, common):\n+ assert common._is_renamed(\"movie.mkv\", \"Movie.2026.1080p.BluRay.x264-GRP\") is True\n+\n+ def test_renamed_faked_resolution(self, common):\n+ assert common._is_renamed(\"Movie.2026.2160p.BluRay.x264-GRP.mkv\", \"Movie.2026.1080p.BluRay.x264-GRP\") is True\n+\n+ def test_empty_names_never_renamed(self, common):\n+ assert common._is_renamed(\"\", \"Movie-GRP\") is False\n+ assert common._is_renamed(\"Movie-GRP.mkv\", \"\") is False\n+\n+ def test_check_detag_flags_rename(self, common):\n+ # Group matches (not detag/notag) but the on-disk name was changed.\n+ meta = {\"tag\": \"-GRP\"}\n+ with patch.object(\n+ common, \"_get_mediainfo_filename\",\n+ AsyncMock(return_value=(\"Movie.2026.1080p.BluRay.x264-GRP\", \"Movie.2026.2160p.BluRay.x264-GRP.mkv\")),\n+ ):\n+ result = _run(common.check_detag(meta, \"TEST\"))\n+ assert result is True\n+ assert meta[\"detag_info\"][\"type\"] == \"rename\"\n+ assert meta[\"detag_info\"][\"disk_filename\"] == \"Movie.2026.2160p.BluRay.x264-GRP.mkv\"\n+\n+ def test_check_detag_no_rename_when_names_match(self, common):\n+ meta = {\"tag\": \"-GRP\"}\n+ with patch.object(\n+ common, \"_get_mediainfo_filename\",\n+ AsyncMock(return_value=(\"Movie.2026.1080p.BluRay.x264-GRP\", \"Movie.2026.1080p.BluRay.x264-GRP.mkv\")),\n+ ):\n+ result = _run(common.check_detag(meta, \"TEST\"))\n+ assert result is False\n+ assert \"detag_info\" not in meta", "status": "modified"}, {"additions": 27, "deletions": 0, "filename": "upload.py", "patch": "@@ -657,6 +657,33 @@ async def process_meta(meta: Meta, base_dir: str, bot: Any = None) -> Optional[b\n return\n # User overrides — clear so trackers won't skip\n meta.pop(\"detag_info\", None)\n+ elif detection_type == \"rename\":\n+ # --- RENAME: always block, ask confirmation ---\n+ disk_file = detag_info.get(\"disk_filename\", \"\")\n+ console.print(\"[bold yellow]⚠️ RENAME DETECTED[/bold yellow]\")\n+ console.print(\"[bold red]━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[/bold red]\")\n+ console.print(f\"[cyan]On-disk filename:[/cyan] [yellow]{disk_file}[/yellow]\")\n+ console.print(f\"[cyan]Original filename:[/cyan] [yellow]{mi_file}[/yellow]\")\n+ console.print()\n+ console.print(\"[bold white]The file was renamed: its on-disk name differs from the name the release group muxed in.[/bold white]\")\n+ console.print(\"[bold white]This release will be skipped on all trackers unless you override below.[/bold white]\")\n+ console.print(\"[bold red]━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[/bold red]\")\n+ console.print()\n+\n+ # Attended only; unattended already cancelled above.\n+ try:\n+ detag_confirm = cli_ui.ask_yes_no(\"Do you want to proceed anyway?\", default=False)\n+ except EOFError:\n+ console.print(\"\\n[red]Exiting on user request (Ctrl+C)[/red]\")\n+ await cleanup_manager.cleanup()\n+ cleanup_manager.reset_terminal()\n+ sys.exit(1)\n+ if not detag_confirm:\n+ console.print(\"[red]Upload cancelled due to rename detection.[/red]\")\n+ meta[\"we_are_uploading\"] = False\n+ return\n+ # User chose to proceed — clear flag so trackers won't skip\n+ meta.pop(\"detag_info\", None)\n else:\n # --- DETAG: always block, ask confirmation ---\n torrent_grp = detag_info.get(\"torrent_group\", \"?\")", "status": "modified"}], "message": "feat: refuse renamed files before upload (cross-seed integrity)\n\nA file whose on-disk name no longer matches the name the release group\nmuxed into the container (MediaInfo General \"Movie name\"/\"Title\" vs\n\"Complete name\") is now detected at the same early stage as notag/detag\nand always refused: cancelled in unattended mode, prompted in attended,\nskipped per-tracker.\n\nThe comparison is exact (only a trailing media extension is dropped) so\neven a dot-vs-space change counts as a rename — cross-seeding needs\nbyte-identical filenames. Detection is gated on the embedded name\ncarrying a real group tag, to avoid false positives on groups that mux a\nplain human title instead of the release name.\n\nCo-Authored-By: Claude Opus 4.8 ", "sha": "9f42509e3101818c91df2fc9cd582064bf81ee60"}, {"author": "yippee0903", "date": "2026-06-28T12:02:25Z", "files": [{"additions": 17, "deletions": 2, "filename": "src/predb_fr.py", "patch": "@@ -68,6 +68,17 @@ def _our_tmdb(tmdb_id: Any) -> int:\n return 0\n \n \n+# Exact French language codes/names. Mirrors FRENCH.FRENCH_LANG_VALUES but kept\n+# local so this module stays importable without pymediainfo. A prefix test would\n+# wrongly match Frisian/Friulian (\"fry\", \"fur\", \"frisian\"), so we match exactly.\n+_FR_AUDIO_VALUES = frozenset({\"fr\", \"fre\", \"fra\", \"french\", \"français\", \"francais\", \"fr-fr\", \"fr-ca\", \"fr-be\", \"fr-ch\"})\n+\n+\n+def _has_fr_audio(meta: dict[str, Any]) -> bool:\n+ \"\"\"True when the upload has at least one French audio track.\"\"\"\n+ return any(str(lang).strip().lower().replace(\"_\", \"-\") in _FR_AUDIO_VALUES for lang in (meta.get(\"audio_languages\") or []))\n+\n+\n def tmdb_debug_line(releases: list[dict[str, Any]], *, tmdb_id: Any, category: Any, tracker: str) -> str:\n \"\"\"One ``--debug`` line spelling out what predb.fr can say about our TMDB id.\n \n@@ -94,6 +105,7 @@ def analyze(\n tmdb_id: Any,\n group: Any,\n category: Any,\n+ has_fr_audio: bool = True,\n ) -> tuple[list[str], list[str]]:\n \"\"\"Compare predb candidates to our submission.\n \n@@ -123,8 +135,10 @@ def analyze(\n # Nuke only reported for same-group candidates to avoid noise.\n blocking.extend(f\"Nuked release on the FR scene: {r.get('name')} — {r['nuke_reason']}\" for r in ours if r.get(\"nuke_reason\"))\n \n- # Group reputation is advisory only.\n- if ours and not any(r.get(\"team_profilarr_validated\") for r in ours):\n+ # Group reputation is advisory only, and only meaningful for French-audio\n+ # releases: FR trackers also take VOSTFR (English audio + FR subs) whose\n+ # groups are English teams that predb.fr legitimately won't have validated.\n+ if has_fr_audio and ours and not any(r.get(\"team_profilarr_validated\") for r in ours):\n info.append(f\"Group {group} is not profilarr-validated on predb.fr.\")\n \n return blocking, info\n@@ -249,6 +263,7 @@ async def crosscheck(meta: dict[str, Any], config: dict[str, Any], tracker: str)\n tmdb_id=our_tmdb_id,\n group=meta.get(\"tag\"),\n category=meta.get(\"category\"),\n+ has_fr_audio=_has_fr_audio(meta),\n )\n for w in info:\n console.print(f\"[yellow]⚠️ predb.fr [{tracker}]: {w}[/yellow]\")", "status": "modified"}, {"additions": 26, "deletions": 0, "filename": "tests/test_predb_fr.py", "patch": "@@ -85,6 +85,32 @@ def test_unvalidated_group_is_advisory_not_blocking():\n assert any(\"not profilarr-validated\" in w for w in info)\n \n \n+def test_unvalidated_group_silent_without_fr_audio():\n+ # VOSTFR upload (English audio): the ENG group is legitimately unvalidated,\n+ # so the advisory must be suppressed.\n+ blocking, info = analyze(\n+ [_rel(team_profilarr_validated=False)], tmdb_id=207, group=\"-T4KT\", category=\"MOVIE\", has_fr_audio=False\n+ )\n+ assert blocking == []\n+ assert info == []\n+\n+\n+def test_has_fr_audio_detection():\n+ from src.predb_fr import _has_fr_audio\n+\n+ # Accepted French variants (codes and names, any case/separator).\n+ assert _has_fr_audio({\"audio_languages\": [\"English\", \"French\"]})\n+ assert _has_fr_audio({\"audio_languages\": [\"fr-FR\"]})\n+ assert _has_fr_audio({\"audio_languages\": [\"fra\"]})\n+ assert _has_fr_audio({\"audio_languages\": [\"français\"]})\n+ assert _has_fr_audio({\"audio_languages\": [\"FR_CA\"]})\n+ # Non-French values that merely start with \"fr\" must be rejected.\n+ assert not _has_fr_audio({\"audio_languages\": [\"Frisian\"]})\n+ assert not _has_fr_audio({\"audio_languages\": [\"Friulian\", \"fry\"]})\n+ assert not _has_fr_audio({\"audio_languages\": [\"English\", \"Japanese\"]})\n+ assert not _has_fr_audio({})\n+\n+\n def test_tv_category_matches_series():\n rels = [_rel(categ=\"Series\", media_id=\"tv:999\")]\n blocking, _ = analyze(rels, tmdb_id=72879, group=\"-T4KT\", category=\"TV\")", "status": "modified"}], "message": "Merge branch 'master' into feat/refuse-renamed-files", "sha": "694128384aba2e96cc4461cdf0e1a6dd9955786b"}], "post_review_commits": ["a310b86278b04e3806537ba2241481d8cb846d77"], "pr_author": "yippee0903", "pr_title": "feat: refuse renamed files before upload (cross-seed integrity)", "repo_name": "yippee0903/Upload-Assistant"}, "repo": "yippee0903/Upload-Assistant", "snapshot": "snapshots/041c0f37d16e21563659000d374881a6c10b58c328512084b1367565701a5e2b.pack", "split": "eval", "task_id": "2633420d509a201e91e09ee10c0e47094f4e62984b5e716f6a44691679eb12a2"} {"base_sha": "ebf57e67441bb8606668daffb6f31759cda952bc", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/timnik82/coimbra-sandal-tracker/pull/1", "id": "28a4c36131b4c39829e3d68fd420b626c7c49f5b33f9f4737461cb467c39393a", "preparation_mode": "source-only", "snapshot": {"base_ref": "ebf57e67441bb8606668daffb6f31759cda952bc", "base_sha": "ebf57e67441bb8606668daffb6f31759cda952bc", "body": "", "head_ref": "52b452fff84e8211f12194b1874a343531511b63", "head_sha": "52b452fff84e8211f12194b1874a343531511b63", "name": "coimbra-sandal-tracker", "number": 1, "owner": "timnik82", "pr_url": "https://github.com/timnik82/coimbra-sandal-tracker/pull/1", "title": ""}}, "head_sha": "52b452fff84e8211f12194b1874a343531511b63", "metadata": {"group_id": "0e10d449d3794894327fc7558a36bf42fb0af47b8ee8cf3c534b145e24020929", "snapshot": {"base_sha": "ebf57e67441bb8606668daffb6f31759cda952bc", "external_requirements": [], "head_sha": "52b452fff84e8211f12194b1874a343531511b63", "objects": 103, "objects_sha256": "543ec8d8ebd4dfb20d02132a3e86143a1dfc7ff503437c15edf94a1375d32cc3", "patch_sha256": "e1b544ffdbbfe7057f2ac47435d99c00f6ea741c813c30ef84267b036623c9d4"}}, "pr_number": 1, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "d43ce205edee", "description": "Remote state PUT requests could overlap, allowing an older save to finish after a newer one and overwrite the latest state.", "file_path": "public/tracker.html"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "d43ce205edee", "description": "When the initial remote load detected a local edit, it canceled the pending debounced save and issued an immediate PUT. If that PUT failed, no pending save remained to send the edit.", "file_path": "public/tracker.html"}], "commits_under_review": [{"author": "timnik82", "date": "2026-08-29T20:30:05Z", "files": [{"additions": 11, "deletions": 0, "filename": "AGENTS.md", "patch": "@@ -16,6 +16,17 @@ Before starting any new sandal search:\n 6. Append every meaningful search run to the `searchLog` array in\n `public/tracker.html`: use the actual date, connector/source, a concise query\n summary, what the run added or confirmed, and the rejection rule applied.\n+7. Keep every product's structured availability fields complete. Use an ISO\n+ date or `null` for `lastChecked`, a finite EUR number or `null` for\n+ `priceEur`, and a string or `null` for `retailer` and `evidenceUrl`.\n+8. Size states are `in_stock`, `size_exists`, `out_of_stock`, or `unknown`.\n+ Portugal delivery is `confirmed`, `unavailable`, or `unknown`; Coimbra\n+ try-on is `confirmed`, `possible`, `unavailable`, or `unknown`; office\n+ suitability is `good`, `acceptable`, `sporty`, or `unknown`.\n+9. Never infer a structured value from words such as “comfort” or “cushioned”.\n+ When the cited source does not confirm a fact, keep it explicitly unknown.\n+10. Comparison selections are user state. Keep `compareIds` unique, limited to\n+ four existing catalogue IDs, and synchronized with `sortBy` in preferences.\n \n User-specific notes, favourites, filters, statuses, and archive flags are stored\n in D1 through `/api/state`. Browser storage is fallback-only.", "status": "modified"}, {"additions": 19, "deletions": 2, "filename": "README.md", "patch": "@@ -5,9 +5,13 @@\n ## Возможности\n \n - компактные раскрывающиеся карточки моделей;\n-- фильтры по пригодности и статусу просмотра;\n+- фильтры по пригодности и статусу просмотра, а также сортировка по актуальности,\n+ цене, амортизации и доступности;\n+- структурированные отметки цены, размеров 46/47, доставки в Португалию,\n+ примерки в Коимбре, офисного вида и даты проверки;\n+- выбор от двух до четырёх моделей и сравнительная таблица;\n - отметки «интересно», «хочу примерить» и «к покупке»;\n-- личные заметки, сохраняемые только в браузере;\n+- личные заметки с удалённой синхронизацией и резервным сохранением в браузере;\n - отдельный архив исключённых моделей с объяснением причин;\n - пользовательский архив просмотренных моделей с возможностью восстановления;\n - синхронизация заметок, фаворитов, статусов и фильтров между устройствами;\n@@ -21,6 +25,19 @@\n Отклонённые и недостаточно подтверждённые модели остаются в каталоге и при\n первом открытии автоматически помещаются в пользовательский архив.\n \n+Каждая модель содержит структурированные поля `lastChecked`, `priceEur`,\n+`retailer`, `size46`, `size47`, `portugalDelivery`, `coimbraTryOn`,\n+`officeSuitability` и `evidenceUrl`. Если источник не подтверждает значение,\n+оно должно оставаться `null` или `unknown` — свободный текст и маркетинговые\n+формулировки не считаются доказательством.\n+\n+Допустимые статусы размеров: `in_stock`, `size_exists`, `out_of_stock`,\n+`unknown`; доставки: `confirmed`, `unavailable`, `unknown`; примерки:\n+`confirmed`, `possible`, `unavailable`, `unknown`; офисного вида: `good`,\n+`acceptable`, `sporty`, `unknown`. Выбранная сортировка и до четырёх моделей\n+для сравнения входят в пользовательские настройки и синхронизируются через\n+`/api/state` без отдельной миграции базы.\n+\n ## Локальный запуск\n \n ```bash", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "app/page.tsx", "patch": "@@ -3,7 +3,7 @@ export default function Home() {\n
\n \n
", "status": "modified"}, {"additions": 342, "deletions": 67, "filename": "public/tracker.html", "patch": "@@ -168,6 +168,10 @@\n .pill.medium { color: #76500a; background: #fff0bd; }\n .pill.unknown { color: #5d6570; background: #e9eef1; }\n .pill.rejected { color: #823636; background: #f8dcdc; }\n+ .pill.fresh { color: #176348; background: #dff3e9; }\n+ .pill.aging { color: #76500a; background: #fff0bd; }\n+ .pill.stale { color: #823636; background: #f8dcdc; }\n+ .pill.confirmed { color: #176348; background: #dff3e9; }\n \n .grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; padding-bottom: 70px; }\n .card {\n@@ -249,6 +253,18 @@\n .source { margin-top: 14px; font-size: .8125rem; color: var(--muted); }\n \n .controls { margin-top: auto; padding: 15px 21px 20px; border-top: 1px solid var(--line); background: rgba(244,248,250,.65); }\n+ .compare-choice {\n+ display: inline-flex;\n+ align-items: center;\n+ gap: 8px;\n+ min-height: 36px;\n+ margin-bottom: 9px;\n+ color: var(--blue-dark);\n+ font-weight: 750;\n+ cursor: pointer;\n+ }\n+ .compare-choice input { width: 18px; height: 18px; accent-color: var(--blue); }\n+ .compare-choice:has(input:disabled) { color: var(--muted); cursor: not-allowed; }\n .control-row { display: grid; grid-template-columns: 1fr auto; gap: 9px; }\n .status {\n width: 100%;\n@@ -286,6 +302,63 @@\n background: white; color: var(--ink); line-height: 1.4;\n }\n .empty { display: none; grid-column: 1 / -1; padding: 48px; text-align: center; color: var(--muted); }\n+ .compare-bar {\n+ position: fixed;\n+ left: 50%;\n+ bottom: max(16px, env(safe-area-inset-bottom));\n+ z-index: 12;\n+ display: flex;\n+ align-items: center;\n+ gap: 10px;\n+ width: min(720px, calc(100% - 28px));\n+ padding: 10px 12px 10px 16px;\n+ border: 1px solid #a9dbe4;\n+ border-radius: 16px;\n+ background: rgba(255,255,255,.96);\n+ box-shadow: 0 18px 48px rgba(20,50,68,.2);\n+ backdrop-filter: blur(16px);\n+ transform: translateX(-50%);\n+ }\n+ .compare-bar[hidden] { display: none; }\n+ body:has(.compare-bar:not([hidden])) .grid { padding-bottom: 150px; }\n+ .compare-summary { min-width: 0; flex: 1; }\n+ .compare-summary strong { display: block; }\n+ .compare-summary span { color: var(--muted); font-size: .78rem; }\n+ .compare-bar button,\n+ .compare-dialog button {\n+ border: 1px solid var(--line);\n+ border-radius: 9px;\n+ background: white;\n+ color: var(--ink);\n+ padding: 7px 11px;\n+ cursor: pointer;\n+ }\n+ .compare-bar .primary { border-color: var(--blue); background: var(--blue); color: white; font-weight: 800; }\n+ .compare-bar .primary:disabled { border-color: var(--line); background: #e9eef1; color: var(--muted); cursor: not-allowed; }\n+ .compare-dialog {\n+ width: min(1080px, calc(100% - 28px));\n+ max-height: min(820px, calc(100dvh - 32px));\n+ padding: 0;\n+ border: 1px solid var(--line);\n+ border-radius: 20px;\n+ background: white;\n+ color: var(--ink);\n+ box-shadow: 0 24px 80px rgba(20,50,68,.28);\n+ }\n+ .compare-dialog::backdrop { background: rgba(20,38,53,.45); backdrop-filter: blur(3px); }\n+ .compare-dialog-shell { display: flex; flex-direction: column; max-height: inherit; }\n+ .compare-dialog-header { display: flex; align-items: center; gap: 14px; padding: 16px 18px; border-bottom: 1px solid var(--line); }\n+ .compare-dialog-header h2 { flex: 1; margin: 0; }\n+ .compare-table-wrap { overflow: auto; overscroll-behavior: contain; padding: 0 18px 18px; }\n+ .compare-table { width: 100%; min-width: 720px; border-collapse: collapse; font-size: .875rem; }\n+ .compare-table th, .compare-table td { padding: 11px 12px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }\n+ .compare-table thead th { position: sticky; top: 0; z-index: 2; background: white; color: var(--blue-dark); }\n+ .compare-table th[scope=\"row\"] { position: sticky; left: 0; z-index: 1; width: 160px; background: white; }\n+ .compare-table .model-heading { min-width: 170px; }\n+ .compare-actions { display: grid; gap: 7px; }\n+ .compare-actions a { color: var(--blue-dark); font-weight: 800; }\n+ .compare-actions button { min-height: 34px; width: fit-content; }\n+ .compare-actions button[data-selected=\"true\"] { color: var(--green); border-color: #acd5c7; background: #edf8f3; }\n footer { padding: 0 0 50px; color: var(--muted); font-size: .8125rem; line-height: 1.5; }\n \n @media (max-width: 760px) {\n@@ -300,6 +373,9 @@\n .foam-rule { grid-template-columns: 1fr; }\n .foam-icon { display: none; }\n .toolbar { position: static; }\n+ .compare-bar { align-items: stretch; flex-wrap: wrap; }\n+ .compare-summary { width: 100%; flex-basis: 100%; }\n+ .compare-bar button { flex: 1; }\n }\n @media (prefers-reduced-motion: no-preference) {\n .card { transition: transform .18s ease, box-shadow .18s ease; }\n@@ -354,6 +430,13 @@

Не потерять хорошую пару

\n \n \n \n+ \n \n \n \n@@ -379,132 +462,175 @@

Не потерять хорошую пару

\n На опубликованном сайте отметки синхронизируются с приватной учётной записью; браузерное сохранение остаётся резервной копией. Цены и наличие меняются; карточка фиксирует только то, что было найдено в этой сессии. Амортизация обуви не гарантирует уменьшения боли в коленях — окончательное решение лучше принимать после примерки и ходьбы.\n \n \n+ \n+\n+ \n+
\n+
\n+

Сравнение моделей

\n+ \n+
\n+
\n+
\n+
\n+\n \n+ {MSG_A_0014}\n+ \"\"\"\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ assert user.is_digest_subscriber is False\n+ analysis_mock.assert_called_once_with(\n+ user=user,\n+ is_superuser=False,\n+ auth_type=AuthTokenType.USER,\n+ )\n+\n+\n+def test_unsubscribe__incorrect_token__ok(api_client):\n+\n+ # arrange\n+ user = create_test_owner()\n+ expected = f\"\"\"\n+ \n+ {MSG_A_0008}\n+ \"\"\"\n+\n+ # act\n+ response = api_client.get(\n+ '/accounts/digest/unsubscribe?token=12345',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ assert user.is_digest_subscriber is True\n+\n+\n+def test_unsubscribe__no_token__ok(api_client):\n+\n+ # arrange\n+ user = create_test_owner()\n+ expected = f\"\"\"\n+ \n+ {MSG_A_0008}\n+ \"\"\"\n+\n+ # act\n+ response = api_client.get(\n+ '/accounts/digest/unsubscribe',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ assert user.is_digest_subscriber is True", "status": "added"}, {"additions": 104, "deletions": 0, "filename": "backend/src/accounts/tests/views/test_unsubscribe_email.py", "patch": "@@ -0,0 +1,104 @@\n+import pytest\n+from django.conf import settings\n+\n+from src.accounts.messages import MSG_A_0008, MSG_A_0014\n+from src.accounts.tokens import UnsubscribeEmailToken\n+from src.analysis.enums import MailoutType\n+from src.processes.tests.fixtures import create_test_owner\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+@pytest.mark.parametrize(\n+ 'email_type', [\n+ MailoutType.TASKS_DIGEST,\n+ MailoutType.WF_DIGEST,\n+ MailoutType.COMMENTS,\n+ MailoutType.NEW_TASK,\n+ ],\n+)\n+def test_unsubscribe__ok(api_client, email_type):\n+\n+ # arrange\n+ user = create_test_owner()\n+ token = str(UnsubscribeEmailToken.create_token(\n+ user_id=user.id,\n+ email_type=email_type,\n+ ))\n+ expected = f\"\"\"\n+ \n+ {MSG_A_0014}\n+ \"\"\"\n+\n+ # act\n+ response = api_client.get(\n+ '/accounts/emails/unsubscribe'\n+ f'?token={token}',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ attribute = MailoutType.MAP[email_type]\n+ assert getattr(user, attribute, None) is False\n+\n+\n+def test_unsubscribe__incorrect_token__ok(api_client):\n+\n+ # arrange\n+ user = create_test_owner()\n+ expected = f\"\"\"\n+ \n+ {MSG_A_0008}\n+ \"\"\"\n+\n+ # act\n+ response = api_client.get(\n+ '/accounts/emails/unsubscribe?token=12345',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ assert user.is_digest_subscriber is True\n+ assert user.is_tasks_digest_subscriber is True\n+ assert user.is_comments_mentions_subscriber is True\n+ assert user.is_new_tasks_subscriber is True\n+ assert user.is_complete_tasks_subscriber is True\n+ assert user.is_newsletters_subscriber is True\n+ assert user.is_special_offers_subscriber is True\n+\n+\n+def test_unsubscribe__no_token__ok(api_client):\n+\n+ # arrange\n+ user = create_test_owner()\n+ expected = f\"\"\"\n+ \n+ {MSG_A_0008}\n+ \"\"\"\n+\n+ # act\n+ response = api_client.get(\n+ '/accounts/emails/unsubscribe',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert response.content.decode('utf-8') == expected\n+ user.refresh_from_db()\n+ assert user.is_digest_subscriber is True\n+ assert user.is_tasks_digest_subscriber is True\n+ assert user.is_comments_mentions_subscriber is True\n+ assert user.is_new_tasks_subscriber is True\n+ assert user.is_complete_tasks_subscriber is True\n+ assert user.is_newsletters_subscriber is True\n+ assert user.is_special_offers_subscriber is True", "status": "added"}, {"additions": 0, "deletions": 528, "filename": "backend/src/accounts/tests/views/test_users/test_api_key.py", "patch": "@@ -1,528 +0,0 @@\n-from datetime import timedelta\n-\n-import pytest\n-from django.utils import timezone\n-\n-from src.accounts.enums import (\n- BillingPlanType,\n- UserStatus,\n- UserType,\n-)\n-from src.accounts.messages import (\n- MSG_A_0035,\n- MSG_A_0036,\n- MSG_A_0041,\n-)\n-from src.accounts.models import APIKey\n-from src.authentication.tokens import PneumaticToken\n-from src.generics.messages import MSG_GE_0001\n-from src.processes.tests.fixtures import (\n- create_invited_user,\n- create_test_account,\n- create_test_admin,\n- create_test_group,\n- create_test_guest,\n- create_test_not_admin,\n- create_test_owner,\n-)\n-\n-pytestmark = pytest.mark.django_db\n-\n-\n-def test_api_key__ok(api_client):\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- api_key = APIKey.objects.create(\n- user=owner,\n- name=owner.get_full_name(),\n- account_id=owner.account_id,\n- key=PneumaticToken.create(owner, for_api_key=True),\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['first_name'] == owner.first_name\n- assert data['last_name'] == owner.last_name\n- assert data['email'] == owner.email\n- assert data['is_admin'] == owner.is_admin\n- assert data['is_account_owner'] == owner.is_account_owner\n- assert data['api_key'] == api_key.key\n- assert data['type'] == owner.type\n- assert data['status'] == owner.status\n-\n-\n-def test_api_key__pagination__ok(api_client):\n-\n- \"\"\" Pagination parameters limit=2 offset=1 are ignored \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- create_test_admin(account=account)\n- create_test_not_admin(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'limit': 2, 'offset': 1},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 3\n-\n-\n-def test_api_key__user_without_api_key__ok(api_client):\n-\n- \"\"\" User without APIKey — api_key field is null \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['email'] == owner.email\n- assert response.data[0]['api_key'] is None\n-\n-\n-def test_api_key__account_scope__ok(api_client):\n-\n- \"\"\" Only users from the requester's account are returned \"\"\"\n-\n- # arrange\n- account_1 = create_test_account(name='Account 1')\n- owner_1 = create_test_owner(account=account_1)\n- account_2 = create_test_account(name='Account 2')\n- create_test_owner(\n- account=account_2,\n- email='owner2@test.test',\n- )\n- create_test_not_admin(\n- account=account_2,\n- email='user2@test.test',\n- )\n- api_client.token_authenticate(owner_1)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['email'] == owner_1.email\n-\n-\n-def test_api_key__invited_users_included__ok(api_client):\n-\n- \"\"\" Users with a pending UserInvite are included in results \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invited_user = create_invited_user(\n- user=owner,\n- email='invited@test.test',\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 2\n- # default ordering: last_name asc; '' < 'Doe'\n- assert response.data[0]['email'] == invited_user.email\n- assert response.data[1]['email'] == owner.email\n-\n-\n-def test_api_key__filter_type_user__ok(api_client):\n-\n- \"\"\" Filter type=user returns only regular users \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- create_test_guest(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'type': UserType.USER},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['type'] == UserType.USER\n- assert response.data[0]['email'] == owner.email\n-\n-\n-def test_api_key__filter_type_guest__ok(api_client):\n-\n- \"\"\" Filter type=guest returns only guest users \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- guest = create_test_guest(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'type': UserType.GUEST},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['type'] == UserType.GUEST\n- assert response.data[0]['email'] == guest.email\n-\n-\n-def test_api_key__filter_status_active__ok(api_client):\n-\n- \"\"\" Filter status=active returns only active users \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- create_test_not_admin(\n- account=account,\n- email='inactive@test.test',\n- status=UserStatus.INACTIVE,\n- )\n- create_invited_user(user=owner, email='invited@test.test')\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'status': UserStatus.ACTIVE},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['status'] == UserStatus.ACTIVE\n- assert response.data[0]['email'] == owner.email\n-\n-\n-def test_api_key__filter_status_invited__ok(api_client):\n-\n- \"\"\" Filter status=invited returns only invited users \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invited_user = create_invited_user(\n- user=owner,\n- email='invited@test.test',\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'status': UserStatus.INVITED},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['status'] == UserStatus.INVITED\n- assert response.data[0]['email'] == invited_user.email\n-\n-\n-def test_api_key__filter_status_inactive__ok(api_client):\n-\n- \"\"\" Filter status=inactive returns only inactive users \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- inactive_user = create_test_not_admin(\n- account=account,\n- email='inactive@test.test',\n- status=UserStatus.INACTIVE,\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'status': UserStatus.INACTIVE},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['status'] == UserStatus.INACTIVE\n- assert response.data[0]['email'] == inactive_user.email\n-\n-\n-def test_api_key__filter_groups__ok(api_client):\n-\n- \"\"\" Filter groups returns only users belonging to the group \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- user_in_group = create_test_not_admin(\n- account=account,\n- email='ingroup@test.test',\n- )\n- create_test_not_admin(\n- account=account,\n- email='outside@test.test',\n- )\n- group = create_test_group(\n- account=account,\n- users=[user_in_group],\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path=f'/accounts/users/api-key?groups={group.id}',\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['email'] == user_in_group.email\n-\n-\n-def test_api_key__ordering_first_name__ok(api_client):\n-\n- \"\"\" ordering=first_name sorts results ascending by first name \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(\n- account=account,\n- first_name='Beta',\n- )\n- user_1 = create_test_not_admin(\n- account=account,\n- email='alpha@test.test',\n- first_name='Alpha',\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'ordering': 'first_name'},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert response.data[0]['email'] == user_1.email\n- assert response.data[1]['email'] == owner.email\n-\n-\n-def test_api_key__ordering_last_name_desc__ok(api_client):\n-\n- \"\"\" ordering=-last_name sorts results descending by last name \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(\n- account=account,\n- last_name='Alpha',\n- )\n- user_1 = create_test_not_admin(\n- account=account,\n- email='beta@test.test',\n- last_name='Beta',\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'ordering': '-last_name'},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert response.data[0]['email'] == user_1.email\n- assert response.data[1]['email'] == owner.email\n-\n-\n-def test_api_key__ordering_status__ok(api_client):\n-\n- \"\"\" ordering=status sorts results ascending by status value \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invited_user = create_invited_user(\n- user=owner,\n- email='invited@test.test',\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path='/accounts/users/api-key',\n- data={'ordering': 'status'},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- # 'active' < 'invited' lexicographically\n- assert response.data[0]['email'] == owner.email\n- assert response.data[1]['email'] == invited_user.email\n-\n-\n-def test_api_key__unauthenticated__permission_denied(api_client):\n-\n- \"\"\" Permission: unauthenticated request is rejected \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- create_test_owner(account=account)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 401\n-\n-\n-def test_api_key__non_owner__permission_denied(api_client):\n-\n- \"\"\" Permission: non-owner user is rejected \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- create_test_owner(account=account)\n- admin = create_test_admin(account=account)\n- api_client.token_authenticate(admin)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 403\n- assert response.data['detail'] == MSG_A_0036\n-\n-\n-def test_api_key__expired_subscription__permission_denied(api_client):\n-\n- \"\"\" Permission: expired subscription is rejected \"\"\"\n-\n- # arrange\n- account = create_test_account(\n- plan=BillingPlanType.UNLIMITED,\n- plan_expiration=timezone.now() - timedelta(days=1),\n- )\n- owner = create_test_owner(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 403\n- assert response.data['detail'] == MSG_A_0035\n-\n-\n-def test_api_key__no_billing_plan__permission_denied(api_client):\n-\n- \"\"\" Permission: account without billing plan is rejected \"\"\"\n-\n- # arrange\n- account = create_test_account(plan=None)\n- owner = create_test_owner(account=account)\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get('/accounts/users/api-key')\n-\n- # assert\n- assert response.status_code == 403\n- assert response.data['detail'] == MSG_A_0041\n-\n-\n-def test_api_key__filter_type_invalid__validation_error(api_client):\n-\n- \"\"\" Filter type with invalid value returns 400 \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invalid_type = 'invalid_type'\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path=f'/accounts/users/api-key?type={invalid_type}',\n- )\n-\n- # assert\n- assert response.status_code == 400\n- assert response.data[0] == MSG_GE_0001(invalid_type)\n-\n-\n-def test_api_key__filter_status_invalid__validation_error(api_client):\n-\n- \"\"\" Filter status with invalid value returns 400 \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invalid_status = 'invalid_status'\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path=f'/accounts/users/api-key?status={invalid_status}',\n- )\n-\n- # assert\n- assert response.status_code == 400\n- assert response.data[0] == MSG_GE_0001(invalid_status)\n-\n-\n-def test_api_key__ordering_invalid__validation_error(api_client):\n-\n- \"\"\" Filter ordering with invalid field name returns 400 \"\"\"\n-\n- # arrange\n- account = create_test_account()\n- owner = create_test_owner(account=account)\n- invalid_ordering = 'invalid_field'\n- expected_message = (\n- f'Select a valid choice. {invalid_ordering}'\n- f' is not one of the available choices.'\n- )\n- api_client.token_authenticate(owner)\n-\n- # act\n- response = api_client.get(\n- path=f'/accounts/users/api-key?ordering={invalid_ordering}',\n- )\n-\n- # assert\n- assert response.status_code == 400\n- assert str(response.data['ordering'][0]) == expected_message", "status": "removed"}, {"additions": 0, "deletions": 0, "filename": "backend/src/accounts/tests/views/test_users_api_key/__init__.py", "patch": "", "status": "added"}, {"additions": 186, "deletions": 0, "filename": "backend/src/accounts/tests/views/test_users_api_key/test_create.py", "patch": "@@ -0,0 +1,186 @@\n+import pytest\n+\n+from src.accounts.models import APIKey\n+from src.processes.tests.fixtures import (\n+ create_test_admin,\n+ create_test_not_admin,\n+ create_test_owner,\n+)\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+def test_create__for_user__created(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{member.id}/api-keys',\n+ data={'name': 'Test Key for Member'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 201\n+ assert response.data['name'] == 'Test Key for Member'\n+ assert isinstance(response.data['token'], str)\n+ assert len(response.data['token']) > 16\n+ assert response.data['prefix'] == (\n+ response.data['token'][:16]\n+ )\n+ api_key = APIKey.objects.get(\n+ id=response.data['id'],\n+ )\n+ assert api_key.user_id == member.id\n+ assert api_key.account_id == owner.account_id\n+\n+\n+def test_create__auto_name__created(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{member.id}/api-keys',\n+ data={},\n+ )\n+\n+ # assert\n+ assert response.status_code == 201\n+ assert response.data['name'] == 'API Key #1'\n+\n+\n+def test_create__for_admin__created(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ admin = create_test_admin(\n+ account=owner.account,\n+ email='admin@test.com',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{admin.id}/api-keys',\n+ data={'name': 'Admin Key'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 201\n+ api_key = APIKey.objects.get(\n+ id=response.data['id'],\n+ )\n+ assert api_key.user_id == admin.id\n+\n+\n+def test_create__other_account__not_found(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ other_user = create_test_owner(\n+ email='other@test.com',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{other_user.id}/api-keys',\n+ data={'name': 'Should fail'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 404\n+\n+\n+def test_create__nonexistent__not_found(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ '/accounts/users/999999/api-keys',\n+ data={'name': 'Should fail'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 404\n+\n+\n+def test_create__not_owner__forbidden(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ admin = create_test_admin(\n+ account=owner.account,\n+ email='admin@test.com',\n+ )\n+ api_client.token_authenticate(admin)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{member.id}/api-keys',\n+ data={'name': 'Admin try'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 403\n+\n+\n+def test_create__for_self__created(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.post(\n+ f'/accounts/users/{owner.id}/api-keys',\n+ data={'name': 'Self Key'},\n+ )\n+\n+ # assert\n+ assert response.status_code == 201\n+ api_key = APIKey.objects.get(\n+ id=response.data['id'],\n+ )\n+ assert api_key.user_id == owner.id", "status": "added"}, {"additions": 140, "deletions": 0, "filename": "backend/src/accounts/tests/views/test_users_api_key/test_destroy.py", "patch": "@@ -0,0 +1,140 @@\n+import pytest\n+\n+from src.accounts.models import APIKey\n+from src.authentication.tokens import PneumaticToken\n+from src.processes.tests.fixtures import (\n+ create_test_not_admin,\n+ create_test_owner,\n+)\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+def test_destroy__valid_key__destroyed(\n+ mocker,\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ raw_key = PneumaticToken.create(\n+ user=member,\n+ for_api_key=True,\n+ )\n+ api_key = APIKey.objects.create(\n+ user=member,\n+ name='To revoke',\n+ account_id=member.account_id,\n+ token=raw_key,\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ cache_delete_mock = mocker.patch(\n+ 'src.accounts.services.api_key'\n+ '.PneumaticToken.cache.delete',\n+ )\n+\n+ # act\n+ response = api_client.delete(\n+ f'/accounts/users/{member.id}/api-keys/{api_key.id}',\n+ )\n+\n+ # assert\n+ assert response.status_code == 204\n+ api_key.refresh_from_db()\n+ assert api_key.is_active is False\n+ expected_cache_key = PneumaticToken.encrypt(raw_key)\n+ cache_delete_mock.assert_called_once_with(\n+ expected_cache_key,\n+ )\n+\n+\n+def test_destroy__other_account__not_found(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ other_user = create_test_owner(email='other@test.com')\n+ api_key = APIKey.objects.create(\n+ user=other_user,\n+ name='Other account key',\n+ account_id=other_user.account_id,\n+ token='pn-other_acct_key',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.delete(\n+ f'/accounts/users/{other_user.id}/api-keys/{api_key.id}',\n+ )\n+\n+ # assert\n+ assert response.status_code == 404\n+\n+\n+def test_destroy__already_revoked__not_found(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ api_key = APIKey.objects.create(\n+ user=member,\n+ name='Revoked',\n+ account_id=member.account_id,\n+ token='pn-revoked_key_x',\n+ is_active=False,\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.delete(\n+ f'/accounts/users/{member.id}/api-keys/{api_key.id}',\n+ )\n+\n+ # assert\n+ assert response.status_code == 404\n+\n+\n+def test_destroy__non_admin__forbidden(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ raw_key = PneumaticToken.create(\n+ user=member,\n+ for_api_key=True,\n+ )\n+ api_key = APIKey.objects.create(\n+ user=member,\n+ name='Member Key',\n+ account_id=member.account_id,\n+ token=raw_key,\n+ )\n+ api_client.token_authenticate(member)\n+\n+ # act\n+ response = api_client.delete(\n+ f'/accounts/users/{member.id}/api-keys/{api_key.id}',\n+ )\n+\n+ # assert\n+ assert response.status_code == 403", "status": "added"}, {"additions": 147, "deletions": 0, "filename": "backend/src/accounts/tests/views/test_users_api_key/test_list.py", "patch": "@@ -0,0 +1,147 @@\n+import pytest\n+\n+from src.accounts.models import APIKey\n+from src.authentication.tokens import PneumaticToken\n+from src.processes.tests.fixtures import (\n+ create_test_not_admin,\n+ create_test_owner,\n+)\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+def test_list__valid_user__returned(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ raw_key = PneumaticToken.create(\n+ user=member,\n+ for_api_key=True,\n+ )\n+ api_key = APIKey.objects.create(\n+ user=member,\n+ name='Member Key',\n+ account_id=member.account_id,\n+ token=raw_key,\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.get(\n+ f'/accounts/users/{member.id}/api-keys',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert len(response.data) == 1\n+ data = response.data[0]\n+ assert data['id'] == api_key.id\n+ assert data['name'] == 'Member Key'\n+ assert 'key' not in data\n+ assert 'token' not in data\n+\n+\n+def test_list__empty__returned(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.get(\n+ f'/accounts/users/{member.id}/api-keys',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert len(response.data) == 0\n+\n+\n+def test_list__excludes_revoked__returned(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ APIKey.objects.create(\n+ user=member,\n+ name='Active',\n+ account_id=member.account_id,\n+ token='pn-active_key_xx',\n+ is_active=True,\n+ )\n+ APIKey.objects.create(\n+ user=member,\n+ name='Revoked',\n+ account_id=member.account_id,\n+ token='pn-revoked_key_y',\n+ is_active=False,\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.get(\n+ f'/accounts/users/{member.id}/api-keys',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert len(response.data) == 1\n+ assert response.data[0]['name'] == 'Active'\n+\n+\n+def test_list__deleted_key__excluded(\n+ api_client,\n+ identify_mock,\n+):\n+\n+ # arrange\n+ owner = create_test_owner()\n+ member = create_test_not_admin(\n+ account=owner.account,\n+ email='member@test.com',\n+ )\n+ APIKey.objects.create(\n+ user=member,\n+ name='Deleted',\n+ account_id=member.account_id,\n+ token='pn-deleted_key_12',\n+ is_deleted=True,\n+ )\n+ APIKey.objects.create(\n+ user=member,\n+ name='Active',\n+ account_id=member.account_id,\n+ token='pn-active_key_34',\n+ is_deleted=False,\n+ )\n+ api_client.token_authenticate(owner)\n+\n+ # act\n+ response = api_client.get(\n+ f'/accounts/users/{member.id}/api-keys',\n+ )\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert len(response.data) == 1\n+ assert response.data[0]['name'] == 'Active'", "status": "added"}, {"additions": 0, "deletions": 728, "filename": "backend/src/accounts/tests/views/test_views.py", "patch": "@@ -1,728 +0,0 @@\n-from datetime import timedelta\n-\n-import pytest\n-from django.conf import settings\n-from django.utils import timezone\n-\n-from src.accounts.enums import (\n- NotificationStatus,\n- NotificationType,\n-)\n-from src.accounts.messages import (\n- MSG_A_0008,\n- MSG_A_0014,\n-)\n-from src.accounts.models import (\n- APIKey,\n- Notification,\n-)\n-from src.accounts.serializers.notifications import (\n- NotificationTaskSerializer,\n- NotificationWorkflowSerializer,\n-)\n-from src.accounts.tokens import (\n- DigestUnsubscribeToken,\n- UnsubscribeEmailToken,\n-)\n-from src.analysis.enums import MailoutType\n-from src.authentication.enums import AuthTokenType\n-from src.authentication.tokens import PneumaticToken\n-from src.processes.models.workflows.task import (\n- Delay,\n- Task,\n-)\n-from src.processes.tests.fixtures import (\n- create_test_user,\n- create_test_workflow,\n-)\n-from src.utils.dates import date_format\n-\n-pytestmark = pytest.mark.django_db\n-\n-\n-class TestAPIKeyGenerationView:\n-\n- def test_api_token_created(self, api_client, identify_mock):\n-\n- user = create_test_user()\n- api_key = APIKey.objects.create(\n- user=user,\n- name=user.get_full_name(),\n- account_id=user.account_id,\n- key=PneumaticToken.create(user, for_api_key=True),\n- )\n-\n- api_client.token_authenticate(user)\n- response = api_client.get('/accounts/api-key')\n-\n- token = response.data.get('token')\n- assert api_key.key == token\n-\n-\n-class TestUnsubscribeDigestView:\n-\n- def test_unsubscribe_ok(self, mocker, api_client):\n- user = create_test_user()\n- token = str(DigestUnsubscribeToken.for_user(user))\n- response_content = f\"\"\"\n- \n- {MSG_A_0014}\n- \"\"\"\n- analysis_mock = mocker.patch(\n- 'src.accounts.views.unsubscribes.'\n- 'AnalyticService.users_digest',\n- )\n-\n- # act\n- response = api_client.get(\n- f'/accounts/digest/unsubscribe?token={token}',\n- )\n-\n- assert response.status_code == 200\n- assert response.content == bytes(response_content, 'UTF-8')\n-\n- user.refresh_from_db()\n- assert user.is_digest_subscriber is False\n- analysis_mock.assert_called_with(\n- user=user,\n- is_superuser=False,\n- auth_type=AuthTokenType.USER,\n- )\n-\n- def test_unsub_incorrect_token(self, api_client):\n- user = create_test_user()\n- response = api_client.get('/accounts/digest/unsubscribe?token=12345')\n- response_message = f\"\"\"\n- \n- {MSG_A_0008}\n- \"\"\"\n-\n- assert response.status_code == 200\n- assert response.content == bytes(response_message, 'UTF-8')\n-\n- user.refresh_from_db()\n- assert user.is_digest_subscriber is True\n-\n- def test_unsub_no_token(self, api_client):\n- user = create_test_user()\n- response_message = f\"\"\"\n- \n- {MSG_A_0008}\n- \"\"\"\n-\n- response = api_client.get('/accounts/digest/unsubscribe')\n-\n- assert response.status_code == 200\n- assert response.content == bytes(response_message, 'UTF-8')\n-\n- user.refresh_from_db()\n- assert user.is_digest_subscriber is True\n-\n-\n-class TestUnsubscribeEmailView:\n- @pytest.mark.parametrize(\n- 'email_type', [\n- MailoutType.TASKS_DIGEST,\n- MailoutType.WF_DIGEST,\n- MailoutType.COMMENTS,\n- MailoutType.NEW_TASK,\n- ],\n- )\n- def test_unsub(\n- self,\n- api_client,\n- email_type,\n- ):\n- # arrange\n- user = create_test_user()\n- token = str(UnsubscribeEmailToken.create_token(\n- user_id=user.id,\n- email_type=email_type,\n- ))\n- response_content = f\"\"\"\n- \n- {MSG_A_0014}\n- \"\"\"\n-\n- # act\n- response = api_client.get(\n- f'/accounts/emails/unsubscribe?token={token}',\n- )\n-\n- assert response.status_code == 200\n- assert response.content == bytes(response_content, 'UTF-8')\n-\n- user.refresh_from_db()\n- attribute = MailoutType.MAP[email_type]\n- assert getattr(user, attribute, None) is False\n-\n- def test_unsub_incorrect_token(self, api_client):\n- # arrange\n- user = create_test_user()\n- response_message = f\"\"\"\n- \n- {MSG_A_0008}\n- \"\"\"\n-\n- # act\n- response = api_client.get('/accounts/emails/unsubscribe?token=12345')\n-\n- # assert\n- assert response.status_code == 200\n- assert response.content == bytes(response_message, 'UTF-8')\n-\n- user.refresh_from_db()\n- assert user.is_digest_subscriber is True\n- assert user.is_tasks_digest_subscriber is True\n- assert user.is_comments_mentions_subscriber is True\n- assert user.is_new_tasks_subscriber is True\n- assert user.is_complete_tasks_subscriber is True\n- assert user.is_newsletters_subscriber is True\n- assert user.is_special_offers_subscriber is True\n-\n- def test_unsub_no_token(self, api_client):\n- # arrange\n- user = create_test_user()\n- response_message = f\"\"\"\n- \n- {MSG_A_0008}\n- \"\"\"\n-\n- # act\n- response = api_client.get('/accounts/emails/unsubscribe')\n-\n- # assert\n- assert response.status_code == 200\n- assert response.content == bytes(response_message, 'UTF-8')\n-\n- user.refresh_from_db()\n- assert user.is_digest_subscriber is True\n- assert user.is_tasks_digest_subscriber is True\n- assert user.is_comments_mentions_subscriber is True\n- assert user.is_new_tasks_subscriber is True\n- assert user.is_complete_tasks_subscriber is True\n- assert user.is_newsletters_subscriber is True\n- assert user.is_special_offers_subscriber is True\n-\n-\n-class TestUserNotifications:\n-\n- def test_list__type_comment__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- user_author = create_test_user(\n- email='t@t.t',\n- account=user.account,\n- is_account_owner=False,\n- )\n- workflow = create_test_workflow(user, tasks_count=1)\n- task = workflow.tasks.first()\n- notification = Notification.objects.create(\n- task_json=NotificationTaskSerializer(\n- instance=task,\n- notification_type=NotificationType.COMMENT,\n- ).data,\n- workflow_json=NotificationWorkflowSerializer(\n- instance=task.workflow,\n- ).data,\n- user_id=user.id,\n- account_id=user.account.id,\n- type=NotificationType.COMMENT,\n- text='text',\n- author_id=user_author.id,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['id'] == notification.id\n- assert data['text'] == notification.text\n- assert data['type'] == notification.type\n- assert data['datetime'] == (\n- notification.datetime.strftime(date_format)\n- )\n- assert data['datetime_tsp'] == notification.datetime.timestamp()\n- assert data['status'] == notification.status\n- assert data['author'] == user_author.id\n- assert data['task']['id'] == task.id\n- assert data['task']['name'] == task.name\n- assert data['workflow']['id'] == workflow.id\n- assert data['workflow']['name'] == workflow.name\n-\n- def test_list__type_delay__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- user_author = create_test_user(\n- email='t@t.t',\n- account=user.account,\n- is_account_owner=False,\n- )\n- workflow = create_test_workflow(user, tasks_count=1)\n- task = workflow.tasks.first()\n- delay = Delay.objects.create(\n- task=task,\n- start_date=timezone.now(),\n- duration=timedelta(days=1),\n- workflow=workflow,\n- )\n- notification = Notification.objects.create(\n- task_json=NotificationTaskSerializer(\n- instance=task,\n- notification_type=NotificationType.DELAY_WORKFLOW,\n- ).data,\n- workflow_json=NotificationWorkflowSerializer(\n- instance=task.workflow,\n- ).data,\n- user_id=user.id,\n- account_id=user.account.id,\n- type=NotificationType.DELAY_WORKFLOW,\n- text='text',\n- author_id=user_author.id,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['id'] == notification.id\n- assert data['text'] == notification.text\n- assert data['type'] == notification.type\n- assert data['datetime'] == (\n- notification.datetime.strftime(date_format)\n- )\n- assert data['datetime_tsp'] == notification.datetime.timestamp()\n- assert data['status'] == notification.status\n- assert data['author'] == user_author.id\n-\n- assert data['task']['id'] == task.id\n- assert data['task']['name'] == task.name\n- assert data['task']['delay']['estimated_end_date_tsp'] == (\n- delay.estimated_end_date.timestamp()\n- )\n- assert data['task']['delay']['duration'] == '1 00:00:00'\n- assert data['workflow']['id'] == workflow.id\n- assert data['workflow']['name'] == workflow.name\n-\n- def test_list__type_delay_resumed__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- user_author = create_test_user(\n- email='t@t.t',\n- account=user.account,\n- is_account_owner=False,\n- )\n- workflow = create_test_workflow(user, tasks_count=1)\n- task = workflow.tasks.first()\n- Delay.objects.create(\n- task=task,\n- start_date=timezone.now(),\n- end_date=(timezone.now() + timedelta(hours=2)),\n- duration=timedelta(days=1),\n- workflow=workflow,\n- )\n- delay = Delay.objects.create(\n- task=task,\n- start_date=timezone.now(),\n- duration=timedelta(hours=1),\n- workflow=workflow,\n- )\n- Notification.objects.create(\n- task_json=NotificationTaskSerializer(\n- instance=task,\n- notification_type=NotificationType.DELAY_WORKFLOW,\n- ).data,\n- workflow_json=NotificationWorkflowSerializer(\n- instance=task.workflow,\n- ).data,\n- user_id=user.id,\n- account_id=user.account.id,\n- type=NotificationType.DELAY_WORKFLOW,\n- text='text',\n- author_id=user_author.id,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['task']['delay']['estimated_end_date_tsp'] == (\n- delay.estimated_end_date.timestamp()\n- )\n- assert data['task']['delay']['duration'] == '01:00:00'\n-\n- def test_list__type_due_date_changed__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- user_author = create_test_user(\n- email='t@t.t',\n- account=user.account,\n- is_account_owner=False,\n- )\n- workflow = create_test_workflow(user, tasks_count=1)\n- task = workflow.tasks.first()\n- task.due_date = timezone.now() + timedelta(hours=1)\n- task.save(update_fields=['due_date'])\n-\n- notification = Notification.objects.create(\n- task_json=NotificationTaskSerializer(\n- instance=task,\n- notification_type=NotificationType.DUE_DATE_CHANGED,\n- ).data,\n- workflow_json=NotificationWorkflowSerializer(\n- instance=task.workflow,\n- ).data,\n- user_id=user.id,\n- account_id=user.account.id,\n- type=NotificationType.DUE_DATE_CHANGED,\n- author_id=user_author.id,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['id'] == notification.id\n- assert data['type'] == NotificationType.DUE_DATE_CHANGED\n- assert data['datetime'] == (\n- notification.datetime.strftime(date_format)\n- )\n- assert data['datetime_tsp'] == notification.datetime.timestamp()\n- assert data['author'] == user_author.id\n- assert data['status'] == NotificationStatus.NEW\n- assert data['task']['id'] == task.id\n- assert data['task']['name'] == task.name\n- assert data['task']['due_date_tsp'] == task.due_date.timestamp()\n- assert data['workflow']['id'] == workflow.id\n- assert data['workflow']['name'] == workflow.name\n-\n- def test_list__pagination__return_first_page(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- notification_1 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n- notification_1.datetime = timezone.now() + timedelta(seconds=1)\n- notification_1.save()\n- notification_2 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n- notification_2.datetime = timezone.now() + timedelta(seconds=2)\n- notification_2.save()\n- notification_3 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n- notification_3.datetime = timezone.now() + timedelta(seconds=3)\n- notification_3.save()\n-\n- # act\n- response = api_client.get(\n- '/accounts/notifications',\n- data={\n- 'limit': 1,\n- 'offset': 1,\n- },\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert response.data['count'] == 3\n- assert len(response.data['results']) == 1\n- assert response.data['results'][0]['id'] == notification_2.id\n-\n- def test_list__filter_new__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- status=NotificationStatus.READ,\n- )\n- notification = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n-\n- # act\n- response = api_client.get(\n- '/accounts/notifications',\n- data={'status': NotificationStatus.NEW},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- assert response.data[0]['id'] == notification.id\n-\n- def test_count__filter_new__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- status=NotificationStatus.READ,\n- )\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n-\n- # act\n- response = api_client.get(\n- '/accounts/notifications/count',\n- data={'status': NotificationStatus.NEW},\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert response.data['count'] == 1\n-\n- def test_list__ordering_datetime_desc__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- status=NotificationStatus.READ,\n- )\n- notification = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n-\n- # act\n- response = api_client.get(\n- '/accounts/notifications?ordering=-datetime',\n- )\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 2\n- assert response.data[0]['id'] == notification.id\n-\n- def test_list__ordering_datetime_asc__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- notification = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n-\n- # act\n- response = api_client.get('/accounts/notifications?ordering=datetime')\n- assert response.status_code == 200\n- assert response.data[0]['id'] == notification.id\n-\n- def test_list__remove_task__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- user_author = create_test_user(\n- email='t@t.t',\n- account=user.account,\n- is_account_owner=False,\n- )\n- workflow = create_test_workflow(user)\n- task = workflow.tasks.get(number=1)\n- Delay.objects.create(\n- task=task,\n- start_date=timezone.now(),\n- duration=timedelta(days=1),\n- workflow=workflow,\n- )\n- notification = Notification.objects.create(\n- task_json=NotificationTaskSerializer(\n- instance=task,\n- notification_type=NotificationType.DELAY_WORKFLOW,\n- ).data,\n- workflow_json=NotificationWorkflowSerializer(\n- instance=task.workflow,\n- ).data,\n- user_id=user.id,\n- account_id=user.account.id,\n- type=NotificationType.DELAY_WORKFLOW,\n- text='text',\n- author_id=user_author.id,\n- )\n- Task.objects.filter(id=task.id).delete()\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 200\n- assert len(response.data) == 1\n- data = response.data[0]\n- assert data['id'] == notification.id\n- assert data['task']['id'] == task.id\n- assert data['task']['name'] == task.name\n-\n- def test_delete__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n- notification = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n-\n- # act\n- response = api_client.delete(\n- f'/accounts/notifications/{notification.id}',\n- )\n-\n- # assert\n- assert response.status_code == 204\n- assert Notification.objects.filter(\n- id=notification.id,\n- ).exists() is False\n-\n- def test_delete__not_exist_notification__not_found(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.delete('/accounts/notifications/99999')\n-\n- # assert\n- assert response.status_code == 404\n-\n- def test_list__not_authorized_user__unauthorized(self, api_client):\n-\n- # act\n- response = api_client.get('/accounts/notifications')\n-\n- # assert\n- assert response.status_code == 401\n-\n-\n-class TestNotificationsReadView:\n-\n- def test_read(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- n1 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- status=NotificationStatus.READ,\n- )\n- n2 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.SYSTEM,\n- )\n- n3 = Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.COMMENT,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.post(\n- '/accounts/notifications/read',\n- data={\n- 'notifications': [n1.id, n2.id, n3.id],\n- },\n- )\n-\n- # assert\n- assert response.status_code == 204\n- assert user.notifications.exclude_read().exists() is False\n-\n- def test_read__empty_list__ok(self, api_client):\n-\n- # arrange\n- user = create_test_user()\n- Notification.objects.create(\n- user=user,\n- account=user.account,\n- type=NotificationType.COMMENT,\n- )\n- api_client.token_authenticate(user)\n-\n- # act\n- response = api_client.post(\n- '/accounts/notifications/read',\n- data={\n- 'notifications': [],\n- },\n- )\n-\n- # assert\n- assert response.status_code == 204\n- assert user.notifications.exclude_read().count() == 1\n-\n- def test_read__not_authorized_user__unauthorized(self, api_client):\n- # act\n- response = api_client.post('/accounts/notifications/read')\n-\n- # assert\n- assert response.status_code == 401", "status": "removed"}, {"additions": 11, "deletions": 2, "filename": "backend/src/accounts/urls.py", "patch": "@@ -3,7 +3,7 @@\n from rest_framework.routers import DefaultRouter\n \n from src.accounts.views.accounts import AccountView\n-from src.accounts.views.api_key import APIKeyView\n+from src.accounts.views.api_key import APIKeyViewSet, UserAPIKeyViewSet\n from src.accounts.views.groups import GroupViewSet\n from src.accounts.views.notifications import (\n NotificationsReadView,\n@@ -37,10 +37,19 @@\n NotificationsViewSet,\n basename='notifications',\n )\n+router.register('api-keys', APIKeyViewSet, basename='api-keys')\n \n urlpatterns = [\n path('account', AccountView.as_view()),\n- path('api-key', APIKeyView.as_view()),\n+ path(\n+ 'users//api-keys',\n+ UserAPIKeyViewSet.as_view({'get': 'list', 'post': 'create'}),\n+ ),\n+ path(\n+ 'users//api-keys/',\n+ UserAPIKeyViewSet.as_view({'delete': 'destroy'}),\n+ ),\n+\n # TODO: Deprecated api. Remove in https://my.pneumatic.app/workflows/13920\n path('digest/unsubscribe', UnsubscribeDigestView.as_view()),\n path('emails/unsubscribe', UnsubscribeEmailView.as_view()),", "status": "modified"}, {"additions": 193, "deletions": 7, "filename": "backend/src/accounts/views/api_key.py", "patch": "@@ -1,36 +1,222 @@\n from django.contrib.auth import get_user_model\n-from rest_framework.generics import (\n- ListAPIView,\n+from drf_spectacular.utils import extend_schema\n+from rest_framework.generics import get_object_or_404\n+from rest_framework.mixins import (\n+ CreateModelMixin,\n+ ListModelMixin,\n )\n+from rest_framework.viewsets import GenericViewSet\n \n+from src.accounts.models import APIKey\n from src.accounts.permissions import (\n+ AccountOwnerPermission,\n BillingPlanPermission,\n ExpiredSubscriptionPermission,\n UserIsAdminOrAccountOwner,\n )\n-from src.authentication.permissions import PrivateApiPermission\n+from src.accounts.serializers.api_key import (\n+ APIKeySerializer,\n+)\n+from src.accounts.services.api_key import APIKeyService\n from src.generics.mixins.views import (\n BaseResponseMixin,\n )\n from src.generics.permissions import (\n UserIsAuthenticated,\n )\n+from src.openapi import (\n+ ACCESS_ACCOUNT_OWNER,\n+ ACCESS_ADMIN_BASE,\n+ EMPTY,\n+ FORBIDDEN,\n+ NOT_FOUND,\n+ UNAUTHORIZED,\n+ VALIDATION_ERROR,\n+)\n \n UserModel = get_user_model()\n \n \n-class APIKeyView(\n- ListAPIView,\n+class APIKeyViewSet(\n+ CreateModelMixin,\n+ ListModelMixin,\n+ GenericViewSet,\n BaseResponseMixin,\n ):\n \n permission_classes = (\n- PrivateApiPermission,\n UserIsAuthenticated,\n BillingPlanPermission,\n UserIsAdminOrAccountOwner,\n ExpiredSubscriptionPermission,\n )\n+ serializer_class = APIKeySerializer\n+\n+ def get_queryset(self):\n+ return (\n+ APIKey.objects\n+ .by_user(self.request.user.id)\n+ .active()\n+ )\n+\n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='List API keys',\n+ description=ACCESS_ADMIN_BASE,\n+ responses={\n+ 200: APIKeySerializer(many=True),\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ },\n+ )\n+ def list(self, request, *args, **kwargs):\n+ return super().list(request, *args, **kwargs)\n+\n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='Create API key',\n+ description=ACCESS_ADMIN_BASE,\n+ request=APIKeySerializer,\n+ responses={\n+ 201: APIKeySerializer,\n+ 400: VALIDATION_ERROR,\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ },\n+ )\n+ def create(self, request, *args, **kwargs):\n+ serializer = self.get_serializer(data=request.data)\n+ serializer.is_valid(raise_exception=True)\n+\n+ service = APIKeyService(\n+ user=request.user,\n+ is_superuser=request.is_superuser,\n+ auth_type=request.token_type,\n+ )\n+ api_key = service.create(\n+ name=serializer.validated_data.get('name'),\n+ )\n+\n+ data = APIKeySerializer(api_key).data\n+ return self.response_created(data)\n+\n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='Revoke API key',\n+ description=ACCESS_ADMIN_BASE,\n+ responses={\n+ 200: EMPTY,\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ 404: NOT_FOUND,\n+ },\n+ )\n+ def destroy(self, request, *args, **kwargs):\n+ instance = self.get_object()\n+ service = APIKeyService(\n+ user=request.user,\n+ instance=instance,\n+ is_superuser=request.is_superuser,\n+ auth_type=request.token_type,\n+ )\n+ service.revoke()\n+ return self.response_ok()\n+\n+\n+class UserAPIKeyViewSet(\n+ CreateModelMixin,\n+ ListModelMixin,\n+ GenericViewSet,\n+ BaseResponseMixin,\n+):\n+\n+ permission_classes = (\n+ AccountOwnerPermission,\n+ ExpiredSubscriptionPermission,\n+ BillingPlanPermission,\n+ )\n+ serializer_class = APIKeySerializer\n+\n+ def _get_target_user(self):\n+ return get_object_or_404(\n+ UserModel.include_inactive\n+ .all_account_users(self.request.user.account_id),\n+ id=self.kwargs['user_id'],\n+ )\n+\n+ def get_queryset(self):\n+ return (\n+ APIKey.objects\n+ .by_user(self.kwargs['user_id'])\n+ .filter(account_id=self.request.user.account_id)\n+ .active()\n+ )\n \n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='List API keys for user',\n+ description=ACCESS_ACCOUNT_OWNER,\n+ responses={\n+ 200: APIKeySerializer(many=True),\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ 404: NOT_FOUND,\n+ },\n+ )\n def list(self, request, *args, **kwargs):\n- return self.response_ok({'token': request.user.apikey.key})\n+ # Validate user exists in account, return 404 instead of empty list\n+ self._get_target_user()\n+ return super().list(request, *args, **kwargs)\n+\n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='Create API key for user',\n+ description=ACCESS_ACCOUNT_OWNER,\n+ request=APIKeySerializer,\n+ responses={\n+ 201: APIKeySerializer,\n+ 400: VALIDATION_ERROR,\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ 404: NOT_FOUND,\n+ },\n+ )\n+ def create(self, request, *args, **kwargs):\n+ target_user = self._get_target_user()\n+ serializer = self.get_serializer(data=request.data)\n+ serializer.is_valid(raise_exception=True)\n+\n+ service = APIKeyService(\n+ user=request.user,\n+ is_superuser=request.is_superuser,\n+ auth_type=request.token_type,\n+ )\n+ api_key = service.create(\n+ target_user=target_user,\n+ name=serializer.validated_data.get('name'),\n+ )\n+\n+ data = APIKeySerializer(api_key).data\n+ return self.response_created(data)\n+\n+ @extend_schema(\n+ tags=['Accounts'],\n+ summary='Revoke API key for user',\n+ description=ACCESS_ACCOUNT_OWNER,\n+ responses={\n+ 200: EMPTY,\n+ 401: UNAUTHORIZED,\n+ 403: FORBIDDEN,\n+ 404: NOT_FOUND,\n+ },\n+ )\n+ def destroy(self, request, *args, **kwargs):\n+ instance = self.get_object()\n+ service = APIKeyService(\n+ user=request.user,\n+ instance=instance,\n+ is_superuser=request.is_superuser,\n+ auth_type=request.token_type,\n+ )\n+ service.revoke()\n+ return self.response_ok()", "status": "modified"}, {"additions": 4, "deletions": 28, "filename": "backend/src/accounts/views/users.py", "patch": "@@ -23,7 +23,6 @@\n from src.accounts.queries import CountTemplatesByUserQuery\n from src.accounts.messages import MSG_A_0052\n from src.accounts.serializers.accounts import AccountCacheSerializer\n-from src.accounts.serializers.api_key import UserAPIKeySerializer\n from src.accounts.serializers.user import (\n UserPrivilegesSerializer,\n UserSerializer,\n@@ -117,12 +116,10 @@ class UsersViewSet(\n 'reassign': ReassignSerializer,\n 'privileges': UserPrivilegesSerializer,\n 'activate_vacation': VacationActivateSerializer,\n- 'api_key': UserAPIKeySerializer,\n }\n action_filterset_classes = {\n 'list': UsersListFilterSet,\n 'privileges': UsersListFilterSet,\n- 'api_key': UsersListFilterSet,\n }\n \n def get_permissions(self):\n@@ -133,7 +130,7 @@ def get_permissions(self):\n IsAuthenticated(),\n BillingPlanPermission(),\n )\n- if self.action in {'privileges', 'api_key'}:\n+ if self.action == 'privileges':\n return (\n AccountOwnerPermission(),\n ExpiredSubscriptionPermission(),\n@@ -181,8 +178,6 @@ def prefetch_queryset(self, queryset, extra_fields=None):\n 'vacations',\n 'vacations__substitute_group__users',\n )\n- elif self.action == 'api_key':\n- queryset = queryset.select_related('apikey')\n return super().prefetch_queryset(\n queryset=queryset,\n extra_fields=extra_fields,\n@@ -195,7 +190,9 @@ def get_queryset(self):\n user = self.request.user\n if self.action == 'transfer':\n queryset = UserModel.objects.all()\n- elif self.action in {'list', 'privileges', 'api_key'}:\n+ elif self.action in {\n+ 'list', 'privileges',\n+ }:\n queryset = (\n UserModel.include_inactive\n .all_account_users(account_id)\n@@ -564,27 +561,6 @@ def count_workflows(self, request, pk=None):\n data={'count': count},\n )\n \n- @extend_schema(\n- tags=['Accounts'],\n- summary='List users API keys',\n- description=ACCESS_ACCOUNT_OWNER,\n- parameters=USERS_LIST_PARAMS,\n- responses={\n- 200: UserAPIKeySerializer(many=True),\n- 401: UNAUTHORIZED,\n- 403: FORBIDDEN,\n- },\n- )\n- @action(\n- detail=False,\n- methods=('get',),\n- url_path='api-key',\n- )\n- def api_key(self, request, *args, **kwargs):\n- queryset = self.filter_queryset(self.get_queryset())\n- serializer = self.get_serializer(queryset, many=True)\n- return self.response_ok(data=serializer.data)\n-\n @extend_schema(\n tags=['Accounts'],\n summary='Active users count',", "status": "modified"}, {"additions": 108, "deletions": 0, "filename": "backend/src/authentication/services/api_key_auth.py", "patch": "@@ -0,0 +1,108 @@\n+from datetime import timedelta\n+from typing import Optional, Tuple\n+\n+from django.core.exceptions import ObjectDoesNotExist\n+from django.utils import timezone, translation\n+from rest_framework.authentication import TokenAuthentication\n+from rest_framework.request import Request\n+\n+from src.accounts.enums import UserStatus\n+from src.accounts.models import APIKey, User\n+from src.authentication.enums import AuthTokenType\n+from src.authentication.tokens import PneumaticToken\n+\n+\n+class APIKeyAuthentication(TokenAuthentication):\n+ \"\"\"Separate auth backend for API key tokens.\n+\n+ Identifies API-key tokens by their prefix (e.g. 'pn-').\n+ If the token does not start with the prefix, returns None\n+ so DRF falls through to the next authentication class.\n+\n+ TODO: When proper request logging is implemented, replace\n+ the last_used_at update with log-based tracking.\n+ \"\"\"\n+\n+ keyword = 'Bearer'\n+\n+ def authenticate(\n+ self,\n+ request: Request,\n+ ) -> Optional[Tuple[User, PneumaticToken]]:\n+ result = super().authenticate(request)\n+ self._apply_auth_context(request, result)\n+ return result\n+\n+ def authenticate_credentials(\n+ self,\n+ key,\n+ ) -> Optional[Tuple[User, PneumaticToken]]:\n+ if isinstance(key, bytes):\n+ key = key.decode('utf-8')\n+\n+ # Only handle tokens with the API key prefix\n+ if not key.startswith(APIKey.API_KEY_PREFIX):\n+ return None\n+\n+ # Check cache first for fast authentication\n+ cached_data = PneumaticToken.data(key)\n+ if cached_data:\n+ try:\n+ user = User.objects.get(pk=cached_data['user_id'])\n+ except ObjectDoesNotExist:\n+ return None\n+ else:\n+ # Fallback to DB (cache miss or eviction)\n+ try:\n+ apikey = APIKey.objects.select_related('user').get(\n+ token=key,\n+ is_active=True,\n+ )\n+ except ObjectDoesNotExist:\n+ return None\n+\n+ if apikey.is_expired:\n+ return None\n+\n+ user = apikey.user\n+\n+ # Populate cache\n+ PneumaticToken.create(\n+ user=user, for_api_key=True, token=key,\n+ )\n+\n+ # Update last_used_at on cache miss (approximate tracking)\n+ # TODO: mark for deletion when the logging system is implemented\n+ now = timezone.now()\n+ if (\n+ apikey.last_used_at is None\n+ or now - apikey.last_used_at > timedelta(hours=1)\n+ ):\n+ APIKey.objects.filter(pk=apikey.pk).update(\n+ last_used_at=now,\n+ )\n+\n+ if user.status != UserStatus.ACTIVE:\n+ return None\n+ return user, PneumaticToken(key, user)\n+\n+ def _apply_auth_context(\n+ self,\n+ request: Request,\n+ result: Optional[Tuple[User, PneumaticToken]],\n+ ) -> None:\n+ \"\"\"Set token_type / is_superuser / session for API key auth.\n+\n+ This backend runs first in the chain. On failure (result=None),\n+ set safe defaults; the next backend will overwrite them.\n+ \"\"\"\n+ if result:\n+ user, _token = result\n+ request.token_type = AuthTokenType.API\n+ request.is_superuser = False\n+ request.session['is_authenticated'] = True\n+ translation.activate(user.language)\n+ else:\n+ request.token_type = None\n+ request.is_superuser = False\n+ request.session['is_authenticated'] = False", "status": "added"}, {"additions": 14, "deletions": 25, "filename": "backend/src/authentication/services/user_auth.py", "patch": "@@ -1,4 +1,4 @@\n-from typing import Any, Optional, Tuple\n+from typing import Any, Optional, Tuple, Union\n \n from django.contrib.auth import get_user_model\n from django.core.exceptions import ObjectDoesNotExist\n@@ -8,7 +8,7 @@\n from rest_framework.request import Request\n \n from src.accounts.enums import UserStatus\n-from src.accounts.models import APIKey, User\n+from src.accounts.models import User\n from src.authentication.enums import (\n AuthTokenType,\n )\n@@ -58,31 +58,20 @@ def authenticate(\n \n def authenticate_credentials(\n self,\n- token: str,\n+ token: Union[bytes, str],\n ) -> Optional[Tuple[UserModel, PneumaticToken]]:\n- # Get active user or api key\n+ if isinstance(token, bytes):\n+ token = token.decode('utf-8')\n+\n cached_data = PneumaticToken.data(token)\n- if cached_data:\n- try:\n- user = UserModel.objects.get(pk=cached_data['user_id'])\n- except ObjectDoesNotExist:\n- return None\n- else:\n- try:\n- apikey = (\n- APIKey.objects\n- .select_related('user')\n- .get(key=token)\n- )\n- user = apikey.user\n- except ObjectDoesNotExist:\n- return None\n-\n- PneumaticToken.create(\n- user=user,\n- for_api_key=True,\n- token=token,\n- )\n+ if not cached_data:\n+ return None\n+\n+ try:\n+ user = UserModel.objects.get(pk=cached_data['user_id'])\n+ except ObjectDoesNotExist:\n+ return None\n+\n if user.status != UserStatus.ACTIVE:\n return None\n return user, PneumaticToken(token, user)", "status": "modified"}, {"additions": 178, "deletions": 0, "filename": "backend/src/authentication/tests/test_api_key_auth.py", "patch": "@@ -0,0 +1,178 @@\n+\"\"\"Unit-tests for APIKeyAuthentication.\"\"\"\n+from datetime import timedelta\n+\n+import pytest\n+from django.utils import timezone\n+\n+from src.accounts.models import APIKey\n+from src.accounts.services.api_key import APIKeyService\n+from src.authentication.services.api_key_auth import APIKeyAuthentication\n+from src.authentication.tokens import PneumaticToken\n+from src.processes.tests.fixtures import create_test_owner\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+def test_authenticate_credentials__ok__auth_returned():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ APIKey.objects.create(\n+ user=user, account=user.account, name='Test',\n+ token=raw_key,\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is not None\n+ auth_user, _auth_token = result\n+ assert auth_user.id == user.id\n+\n+\n+def test_authenticate_credentials__cache_miss__cache_populated():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ APIKey.objects.create(\n+ user=user, account=user.account, name='Test',\n+ token=raw_key,\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is not None\n+ cached = PneumaticToken.data(raw_key)\n+ assert cached is not None\n+ assert cached['user_id'] == user.id\n+\n+\n+def test_authenticate_credentials__wrong_prefix__none():\n+\n+ # arrange\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials('some_random_token')\n+\n+ # assert\n+ assert result is None\n+\n+\n+def test_authenticate_credentials__expired__none():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ APIKey.objects.create(\n+ user=user, account=user.account, name='Expired',\n+ token=raw_key,\n+ expires_at=timezone.now() - timedelta(days=1),\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is None\n+\n+\n+def test_authenticate_credentials__inactive__none():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ APIKey.objects.create(\n+ user=user, account=user.account, name='Inactive',\n+ token=raw_key,\n+ is_active=False,\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is None\n+\n+\n+def test_authenticate_credentials__bytes_token__ok():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ APIKey.objects.create(\n+ user=user, account=user.account, name='Test',\n+ token=raw_key,\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key.encode())\n+\n+ # assert\n+ assert result is not None\n+ assert result[0].id == user.id\n+\n+\n+def test_authenticate_credentials__not_found__none():\n+\n+ # arrange\n+ raw_key = f'{APIKey.API_KEY_PREFIX}nonexistent_key_abc'\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is None\n+\n+\n+def test_authenticate_credentials__first_use__last_used_updated():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+ apikey = APIKey.objects.create(\n+ user=user, account=user.account, name='Test',\n+ token=raw_key,\n+ )\n+ assert apikey.last_used_at is None\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ apikey.refresh_from_db()\n+ assert apikey.last_used_at is not None\n+\n+\n+def test_authenticate_credentials__cache_hit__ok(django_assert_num_queries):\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = APIKeyService.generate_key()\n+\n+ # Pre-populate cache, bypassing DB\n+ PneumaticToken.create(\n+ user=user, for_api_key=True, token=raw_key,\n+ )\n+ auth_service = APIKeyAuthentication()\n+\n+ # act\n+ # 1 query for User.objects.get(pk=user.id), 0 for APIKey\n+ with django_assert_num_queries(1):\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is not None\n+ assert result[0].id == user.id", "status": "added"}, {"additions": 51, "deletions": 42, "filename": "backend/src/authentication/tests/test_auth_middleware.py", "patch": "@@ -9,19 +9,19 @@\n from src.logs.models import AccountEvent\n from src.processes.tests.fixtures import (\n create_test_account,\n- create_test_user,\n+ create_test_owner,\n )\n \n pytestmark = pytest.mark.django_db\n \n \n-def test__user_token_auth__skip(api_client, mocker):\n+def test_middleware__user_token_auth__skip(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -38,15 +38,16 @@ def test__user_token_auth__skip(api_client, mocker):\n # assert\n assert response.status_code == 200\n assert not AccountEvent.objects.all().exists()\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)\n \n \n-def test__api_token_auth__ok(api_client, mocker):\n+def test_middleware__api_token_auth__ok(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -67,7 +68,7 @@ def test__api_token_auth__ok(api_client, mocker):\n account=user.account,\n ip='192.168.0.1',\n user_agent='Firefox',\n- auth_token=user.apikey.key,\n+ auth_token=token,\n scheme='http',\n method='GET',\n path=path,\n@@ -76,15 +77,16 @@ def test__api_token_auth__ok(api_client, mocker):\n direction=RequestDirection.RECEIVED,\n http_status=200,\n )\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)\n \n \n-def test__get_request_with_data__ok(api_client, mocker):\n+def test_middleware__get_request_with_data__ok(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -106,7 +108,7 @@ def test__get_request_with_data__ok(api_client, mocker):\n account=user.account,\n ip='192.168.0.1',\n user_agent='Firefox',\n- auth_token=user.apikey.key,\n+ auth_token=token,\n scheme='http',\n method='GET',\n path=path,\n@@ -116,15 +118,16 @@ def test__get_request_with_data__ok(api_client, mocker):\n direction=RequestDirection.RECEIVED,\n request_data=params,\n )\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)\n \n \n-def test__get_request_with_query_string__ok(api_client, mocker):\n+def test_middleware__get_request_with_query_string__ok(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -145,7 +148,7 @@ def test__get_request_with_query_string__ok(api_client, mocker):\n account=user.account,\n ip='192.168.0.1',\n user_agent='Firefox',\n- auth_token=user.apikey.key,\n+ auth_token=token,\n scheme='http',\n method='GET',\n path=path,\n@@ -155,15 +158,16 @@ def test__get_request_with_query_string__ok(api_client, mocker):\n direction=RequestDirection.RECEIVED,\n request_data={'key_1': 'Value1,Value2', 'key_2': '123'},\n )\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)\n \n \n-def test__post_request_with_data__ok(api_client, mocker):\n+def test_middleware__post_request_with_data__ok(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -185,7 +189,7 @@ def test__post_request_with_data__ok(api_client, mocker):\n account=user.account,\n ip='192.168.0.1',\n user_agent='Firefox',\n- auth_token=user.apikey.key,\n+ auth_token=token,\n scheme='http',\n method='POST',\n path=path,\n@@ -196,14 +200,15 @@ def test__post_request_with_data__ok(api_client, mocker):\n )\n assert event.request_data == data\n assert event.response_data is None\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)\n \n \n-def test__head_request__skip(api_client, mocker):\n+def test_middleware__head_request__skip(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -212,7 +217,7 @@ def test__head_request__skip(api_client, mocker):\n 'for_api_key': True,\n },\n )\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n \n # act\n response = api_client.head(\n@@ -225,15 +230,16 @@ def test__head_request__skip(api_client, mocker):\n # assert\n assert response.status_code == 405\n assert not AccountEvent.objects.all().exists()\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 2)\n \n \n-def test__options_request__skip(api_client, mocker):\n+def test_middleware__options_request__skip(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -255,15 +261,16 @@ def test__options_request__skip(api_client, mocker):\n # assert\n assert response.status_code == 200\n assert not AccountEvent.objects.all().exists()\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 2)\n \n \n-def test__disable_log_api_requests__skip(api_client, mocker):\n+def test_middleware__disable_log_api_requests__skip(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=False)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -279,15 +286,16 @@ def test__disable_log_api_requests__skip(api_client, mocker):\n # assert\n assert response.status_code == 200\n assert not AccountEvent.objects.all().exists()\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 2)\n \n \n-def test__bad_request__save_error(api_client, mocker):\n+def test_middleware__bad_request__save_error(api_client, mocker):\n \n # arrange\n account = create_test_account(log_api_requests=True)\n- user = create_test_user(account=account)\n- api_client.token_authenticate(user, token_type=AuthTokenType.API)\n- mocker.patch(\n+ user = create_test_owner(account=account)\n+ token = api_client.token_authenticate(user, token_type=AuthTokenType.API)\n+ token_data_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.data',\n return_value={\n@@ -309,7 +317,7 @@ def test__bad_request__save_error(api_client, mocker):\n account=user.account,\n ip='192.168.0.1',\n user_agent='Firefox',\n- auth_token=user.apikey.key,\n+ auth_token=token,\n scheme='http',\n method='POST',\n path=path,\n@@ -325,3 +333,4 @@ def test__bad_request__save_error(api_client, mocker):\n assert event.response_data['details']['reason'] == (\n 'This field is required.'\n )\n+ token_data_mock.assert_has_calls([mocker.call(token)] * 3)", "status": "modified"}, {"additions": 40, "deletions": 0, "filename": "backend/src/authentication/tests/test_user_auth.py", "patch": "@@ -0,0 +1,40 @@\n+\"\"\"Unit-tests for PneumaticTokenAuthentication.\"\"\"\n+import pytest\n+\n+from src.authentication.services.user_auth import PneumaticTokenAuthentication\n+from src.authentication.tokens import PneumaticToken\n+from src.processes.tests.fixtures import create_test_owner\n+\n+pytestmark = pytest.mark.django_db\n+\n+\n+def test_authenticate__cache_hit__ok():\n+\n+ # arrange\n+ user = create_test_owner()\n+ raw_key = PneumaticToken.create(user, for_api_key=False)\n+ auth_service = PneumaticTokenAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials(raw_key)\n+\n+ # assert\n+ assert result is not None\n+ assert result[0].id == user.id\n+\n+\n+def test_authenticate__cache_miss__none(mocker):\n+\n+ # arrange\n+ token_data_mock = mocker.patch(\n+ 'src.authentication.tokens.PneumaticToken.data',\n+ return_value=None,\n+ )\n+ auth_service = PneumaticTokenAuthentication()\n+\n+ # act\n+ result = auth_service.authenticate_credentials('no_such_token')\n+\n+ # assert\n+ assert result is None\n+ token_data_mock.assert_called_once_with('no_such_token')", "status": "added"}, {"additions": 0, "deletions": 12, "filename": "backend/src/authentication/tests/test_views/test_signout.py", "patch": "@@ -1,8 +1,6 @@\n import pytest\n \n-from src.accounts.models import APIKey\n from src.authentication.enums import AuthTokenType\n-from src.authentication.tokens import PneumaticToken\n from src.processes.tests.fixtures import (\n create_test_user,\n )\n@@ -14,16 +12,6 @@ def test_signout__user_token__ok(api_client, mocker):\n \n # arrange\n user = create_test_user()\n- token = PneumaticToken.create(\n- user=user,\n- for_api_key=True,\n- )\n- APIKey.objects.create(\n- user=user,\n- account=user.account,\n- name='Token for API',\n- key=token,\n- )\n expire_token_mock = mocker.patch(\n 'src.authentication.tokens.'\n 'PneumaticToken.expire_token',", "status": "modified"}, {"additions": 4, "deletions": 5, "filename": "backend/src/authentication/views/signout.py", "patch": "@@ -1,9 +1,9 @@\n-from django.contrib.auth import get_user_model\n from rest_framework.authentication import get_authorization_header\n from rest_framework.generics import (\n CreateAPIView,\n )\n \n+from src.authentication.enums import AuthTokenType\n from src.authentication.permissions import (\n PrivateApiPermission,\n )\n@@ -15,8 +15,6 @@\n UserIsAuthenticated,\n )\n \n-UserModel = get_user_model()\n-\n \n class SignOutView(\n CreateAPIView,\n@@ -28,7 +26,8 @@ class SignOutView(\n def post(self, request, *args, **kwargs):\n auth = get_authorization_header(request).split()\n token = auth[1].decode()\n- if request.user.apikey.key != token:\n- # API key cannot be expired from logout\n+\n+ # API key tokens should not be expired on logout\n+ if request.token_type != AuthTokenType.API:\n PneumaticToken.expire_token(token)\n return self.response_ok()", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "backend/src/generics/tests/clients.py", "patch": "@@ -21,7 +21,7 @@ def token_authenticate(\n user_agent: str = 'Firefox',\n user_ip: str = '192.168.0.1',\n token: Optional[str] = None,\n- ):\n+ ) -> str:\n \n if not token:\n if token_type == AuthTokenType.API:\n@@ -33,7 +33,7 @@ def token_authenticate(\n user=user,\n account=user.account,\n name='Token for API',\n- key=token,\n+ token=token,\n )\n elif token_type == AuthTokenType.USER:\n token = PneumaticToken.create(", "status": "modified"}, {"additions": 0, "deletions": 2, "filename": "backend/src/openapi/enums.py", "patch": "@@ -15,7 +15,6 @@ class ExcludedPath:\n \"\"\"\n \n WEBHOOKS_BUFFER = '/webhooks/buffer'\n- ACCOUNTS_API_KEY = '/accounts/api-key'\n ACCOUNTS_INVITES_TOKEN = '/accounts/invites/token'\n ACCOUNTS_INVITES = '/accounts/invites'\n ACCOUNTS_DIGEST_UNSUB = '/accounts/digest'\n@@ -46,7 +45,6 @@ class ExcludedPath:\n \n ALL = (\n WEBHOOKS_BUFFER,\n- ACCOUNTS_API_KEY,\n ACCOUNTS_INVITES_TOKEN,\n ACCOUNTS_INVITES,\n ACCOUNTS_DIGEST_UNSUB,", "status": "modified"}, {"additions": 3, "deletions": 21, "filename": "backend/src/openapi/tests/test_preprocessing.py", "patch": "@@ -55,9 +55,9 @@ def test_exclude_private_endpoints__trailing_slash__filtered():\n # arrange\n endpoints = [\n (\n- '/accounts/api-key/',\n- '^/accounts/api-key/$',\n- 'GET',\n+ '/auth/signup/',\n+ '^/auth/signup/$',\n+ 'POST',\n SimpleNamespace(cls=object),\n ),\n ]\n@@ -211,24 +211,6 @@ def get_permissions(self):\n assert result[0][2] == 'POST'\n \n \n-def test_exclude_private_endpoints__api_key__filtered():\n- # arrange\n- endpoints = [\n- (\n- '/accounts/api-key',\n- '^/accounts/api-key$',\n- 'GET',\n- SimpleNamespace(cls=object),\n- ),\n- ]\n-\n- # act\n- result = exclude_private_endpoints(endpoints)\n-\n- # assert\n- assert result == []\n-\n-\n def test_exclude_private_endpoints__callback_no_cls__kept():\n # arrange\n endpoints = [", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "backend/src/processes/queries.py", "patch": "@@ -1161,7 +1161,8 @@ def _get_from(self):\n pt.is_deleted IS FALSE\n )\n LEFT JOIN processes_taskperformer ptp ON (\n- pt.id = ptp.task_id\n+ pt.id = ptp.task_id AND\n+ ptp.is_deleted IS FALSE\n )\n LEFT JOIN accounts_usergroup_users aug ON (\n ptp.group_id = aug.usergroup_id AND", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "backend/src/processes/services/fieldsets/fieldset.py", "patch": "@@ -223,7 +223,7 @@ def _update_fields(\n }\n fields_api_names = set()\n for field_data in fields_data:\n- field_api_name = field_data.pop('api_name', None)\n+ field_api_name = field_data.get('api_name')\n if field_api_name and field_api_name in existing_fields:\n service = FieldTemplateService(\n user=self.user,\n@@ -409,7 +409,7 @@ def update_rules(\n }\n rule_api_names = set()\n for rule_data in rules_data:\n- rule_api_name = rule_data.pop('api_name', None)\n+ rule_api_name = rule_data.get('api_name')\n if rule_api_name and rule_api_name in existing_rules:\n service = FieldsetTemplateRuleService(\n user=self.user,", "status": "modified"}, {"additions": 14, "deletions": 2, "filename": "backend/src/processes/tests/test_services/test_fieldsets/test_fieldset_template_service.py", "patch": "@@ -572,6 +572,7 @@ def test__update_fields__existing_field__ok(mocker):\n )\n field_template_service_partial_update_mock.assert_called_once_with(\n name='Updated Field 1',\n+ api_name=field_1.api_name,\n force_save=True,\n )\n field_template_service_create_mock.assert_not_called()\n@@ -600,7 +601,11 @@ def test__update_fields__new_field__ok(mocker):\n instance=fieldset,\n )\n fields_data = [\n- {'name': 'New Field', 'type': 'number', 'order': 1},\n+ {\n+ 'name': 'New Field',\n+ 'type': 'number', 'order': 1,\n+ 'api_name': 'field-api-name',\n+ },\n ]\n \n # mock\n@@ -633,6 +638,7 @@ def test__update_fields__new_field__ok(mocker):\n field_template_service_create_mock.assert_called_once_with(\n fieldset_id=fieldset.id,\n template_id=template.id,\n+ api_name='field-api-name',\n name='New Field',\n type='number',\n order=1,\n@@ -811,6 +817,7 @@ def test_update_rules__existing_rule__ok(mocker):\n )\n fs_rule_update_mock.assert_called_once_with(\n value='200',\n+ api_name=rule_1.api_name,\n )\n fieldset_template_rule_service_create_mock.assert_not_called()\n \n@@ -837,7 +844,11 @@ def test_update_rules__new_rule__ok(mocker):\n instance=fieldset,\n )\n rules_data = [\n- {'type': FieldSetRuleType.SUM_EQUAL, 'value': '100'},\n+ {\n+ 'type': FieldSetRuleType.SUM_EQUAL,\n+ 'value': '100',\n+ 'api_name': 'rule-api-name',\n+ },\n ]\n \n # mock\n@@ -870,6 +881,7 @@ def test_update_rules__new_rule__ok(mocker):\n fs_rule_create_mock.assert_called_once_with(\n fieldset_id=fieldset.id,\n type=FieldSetRuleType.SUM_EQUAL,\n+ api_name='rule-api-name',\n value='100',\n )\n fs_rule_update_mock.assert_not_called()", "status": "modified"}, {"additions": 27, "deletions": 0, "filename": "backend/src/processes/tests/test_views/test_tasks/test_list.py", "patch": "@@ -1765,6 +1765,33 @@ def test_list__ordering_by_reversed_overdue__ok(api_client):\n assert response.data[2]['id'] == task_11.id\n \n \n+def test_list__soft_deleted_performer__not_shown(api_client):\n+ # arrange\n+ account = create_test_account()\n+ user = create_test_admin(account=account)\n+ workflow = create_test_workflow(user, tasks_count=1)\n+ task = workflow.tasks.get(number=1)\n+ task.taskperformer_set.all().delete()\n+\n+ # Simulate the bug condition: a performer is soft-deleted\n+ # but has a directly_status != DELETED\n+ TaskPerformer.objects.create(\n+ task_id=task.id,\n+ type=PerformerType.USER,\n+ user=user,\n+ directly_status=DirectlyStatus.CREATED,\n+ is_deleted=True,\n+ )\n+ api_client.token_authenticate(user=user)\n+\n+ # act\n+ response = api_client.get('/v3/tasks')\n+\n+ # assert\n+ assert response.status_code == 200\n+ assert len(response.data) == 0\n+\n+\n def test_list__filter_assigned_to__ok(api_client):\n \n # arrange", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "backend/src/settings.py", "patch": "@@ -263,6 +263,8 @@ class Common(Configuration):\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'src.authentication.services.public_auth.PublicAuthService',\n 'src.authentication.services.guest_auth.GuestJWTAuthService',\n+ 'src.authentication.services.api_key_auth.'\n+ 'APIKeyAuthentication',\n 'src.authentication.services.user_auth.'\n 'PneumaticTokenAuthentication',\n 'src.authentication.services.jwt_auth.PneumaticJWTAuthentication',", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/config/common.json", "patch": "@@ -119,7 +119,7 @@\n \"confirmPaymentDetails\": \"/payment/confirm?token=:token\",\n \"startFreeSubscription\": \"/payment/subscription/downgrade-to-free\",\n \"getCustomerPortalLink\": \"/payment/customer-portal?cancel_url=:cancel_url\",\n- \"apiKey\": \"/api/accounts/api-key\",\n+ \"apiKeys\": \"/api/accounts/api-keys/:id?\",\n \"getTasksCount\": \"/accounts/user/counters\",\n \"createKickoffForm\": \"/kickoffs\",\n \"editKickoffForm\": \"/kickoffs/:id/edit\",", "status": "modified"}, {"additions": 5, "deletions": 5, "filename": "frontend/src/public/__stubs__/fieldsets.factory.ts", "patch": "@@ -21,12 +21,12 @@ export const makeFieldsetField = (overrides: Partial = {}): IFie\n export const makeFieldsetRuntime = (overrides: Partial = {}): IFieldsetRuntime => ({\n apiNameBinding: 'fs-1',\n name: 'Fieldset 1',\n+ title: 'Fieldset 1',\n description: '',\n order: 0,\n fields: [],\n labelPosition: EFieldLabelPosition.Top,\n layout: 'vertical',\n- title: '',\n ...overrides,\n });\n \n@@ -43,11 +43,11 @@ export const makeFieldsetCatalogItem = (overrides: Partial\n id: 1,\n apiName: 'fs-1',\n name: 'Test Fieldset',\n+ title: 'Test Fieldset',\n description: '',\n labelPosition: EFieldLabelPosition.Top,\n layout: 'vertical',\n order: 0,\n- title: '',\n rules: [],\n fields: [],\n usage: [],\n@@ -58,11 +58,11 @@ export const makeFieldsetBindingClient = (overrides: Partial = {}):\n apiName: 'catalog-fs-1',\n sharedFieldsetId: 10,\n name: 'Test Fieldset',\n+ title: 'Test Fieldset',\n description: '',\n labelPosition: EFieldLabelPosition.Top,\n layout: 'vertical',\n order: 0,\n- title: '',\n rules: [],\n fields: [],\n ...overrides,\n@@ -86,11 +86,11 @@ export const makeFieldsetTaskAPI = (overrides: Partial = {}):\n id: 100,\n apiName: 'task-fs-1',\n name: 'Task Fieldset',\n+ title: 'Task Fieldset',\n description: '',\n order: 0,\n labelPosition: EFieldLabelPosition.Top,\n layout: 'vertical',\n- title: '',\n fields: [] as IExtraField[],\n ...overrides,\n });", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/__stubs__/templates.factory.ts", "patch": "@@ -1,4 +1,4 @@\n-import { IKickoffClient, ITemplateResponse, ITemplateTask, ITemplateTaskClient } from '../types/template';\n+import { ITemplateKickoffClient, ITemplateResponse, ITemplateTask, ITemplateTaskClient } from '../types/template';\n import { createEmptyTaskDueDate } from '../utils/dueDate/createEmptyTaskDueDate';\n \n export const makeTemplateTaskClient = (overrides: Partial = {}): ITemplateTaskClient => ({\n@@ -42,7 +42,7 @@ export const makeTemplateTask = (overrides: Partial = {}): ITempl\n ...overrides,\n });\n \n-export const makeKickoffClient = (overrides: Partial = {}): IKickoffClient => ({\n+export const makeKickoffClient = (overrides: Partial = {}): ITemplateKickoffClient => ({\n description: '',\n fields: [],\n fieldsets: [],", "status": "modified"}, {"additions": 40, "deletions": 6, "filename": "frontend/src/public/api/getApiKey.ts", "patch": "@@ -1,16 +1,50 @@\n+import { IApiKeyCreateResponse, IApiKeyItem } from '../types/integrations';\n import { commonRequest } from './commonRequest';\n+import { getBrowserConfigEnv } from '../utils/getConfig';\n \n-export interface IGetApiKeyResponse {\n- token: string;\n-}\n+export function getApiKeys() {\n+ const { api: { urls } } = getBrowserConfigEnv();\n+ const url = urls.apiKeys.replace('/:id?', '');\n \n-export function getApiKey() {\n- return commonRequest(\n- 'apiKey',\n+ return commonRequest(\n+ url,\n {},\n {\n type: 'local',\n shouldThrow: true,\n },\n );\n }\n+\n+export function createApiKey(name: string) {\n+ const { api: { urls } } = getBrowserConfigEnv();\n+ const url = urls.apiKeys.replace('/:id?', '');\n+\n+ return commonRequest(\n+ url,\n+ {\n+ method: 'POST',\n+ data: { name },\n+ },\n+ {\n+ type: 'local',\n+ shouldThrow: true,\n+ },\n+ );\n+}\n+\n+export function deleteApiKey(id: number) {\n+ const { api: { urls } } = getBrowserConfigEnv();\n+ const url = urls.apiKeys.replace(':id?', String(id));\n+\n+ return commonRequest(\n+ url,\n+ {\n+ method: 'DELETE',\n+ },\n+ {\n+ type: 'local',\n+ shouldThrow: true,\n+ },\n+ );\n+}", "status": "modified"}, {"additions": 4, "deletions": 0, "filename": "frontend/src/public/components/FieldsetFieldGroup/FieldsetFieldGroup.css", "patch": "@@ -12,6 +12,8 @@\n font-weight: bold;\n line-height: 20px;\n color: #262522;\n+\n+ @mixin text-wrap;\n }\n \n .fieldset-group__description {\n@@ -20,6 +22,8 @@\n font-size: 13px;\n line-height: 18px;\n color: #79756d;\n+\n+ @mixin text-wrap;\n }\n \n .fieldset-group__error {", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.css", "patch": "@@ -64,6 +64,8 @@\n .settings-label {\n font-weight: 600;\n color: var(--pneumatic-color-black72);\n+ display: flex;\n+ gap: 0.4rem;\n \n @mixin text-base;\n }\n@@ -141,6 +143,10 @@\n }\n }\n \n+.settings-input_error {\n+ border-color: var(--pneumatic-color-warning);\n+}\n+\n .empty-text {\n color: var(--pneumatic-color-black48);\n ", "status": "modified"}, {"additions": 60, "deletions": 2, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.tsx", "patch": "@@ -3,6 +3,9 @@ import { useEffect, useState, useMemo, useCallback, ChangeEvent } from 'react';\n import classnames from 'classnames';\n import { useIntl } from 'react-intl';\n import { useDispatch, useSelector } from 'react-redux';\n+import classNames from 'classnames';\n+\n+import { validateFieldsetTitle } from '../../../utils/validators';\n \n import {\n openEditModal,\n@@ -16,7 +19,7 @@ import {\n import { history } from '../../../utils/history';\n import { ERoutes } from '../../../constants/routes';\n \n-import { ModifyDropdown, Button, FilterSelect } from '../../UI';\n+import { ModifyDropdown, Button, FilterSelect, Tooltip } from '../../UI';\n import { EModifyDropdownToggle } from '../../UI/ModifyDropdown/types';\n import { DropdownList } from '../../UI/DropdownList';\n import { NotificationManager } from '../../UI/Notifications';\n@@ -29,6 +32,7 @@ import { getCurrentFieldset, isCurrentFieldsetLoading } from '../../../redux/sel\n import { getAccountId } from '../../../redux/selectors/user';\n \n import { EExtraFieldMode, EExtraFieldType, IExtraField } from '../../../types/template';\n+import { FilledInfoIcon } from '../../icons';\n import { EInputNameBackgroundColor, EMoveDirections } from '../../../types/workflow';\n import {\n IFieldsetTemplateRule,\n@@ -59,6 +63,7 @@ import { TFieldsetDetailsProps, TDetailFieldsetState, TDetailFieldsetChanges } f\n import styles from './FieldsetDetails.css';\n \n const EMPTY_DETAIL_FIELDSET: TDetailFieldsetState = {\n+ title: '',\n description: '',\n labelPosition: EFieldLabelPosition.Top,\n fields: [],\n@@ -106,13 +111,21 @@ const FieldsetDetails = ({\n if (!fieldset) return;\n \n setDetailFieldset({\n+ title: fieldset.title,\n description: fieldset.description || '',\n labelPosition: fieldset.labelPosition,\n fields: normalizeFieldsForUI(fieldset.fields as unknown as IExtraField[]),\n rules: fieldset.rules || [],\n });\n setDetailFieldsetChanges({});\n- }, [fieldset?.id, fieldset?.description, fieldset?.labelPosition, fieldset?.fields, fieldset?.rules]);\n+ }, [fieldset?.id, fieldset?.title, fieldset?.description, fieldset?.labelPosition, fieldset?.fields, fieldset?.rules]);\n+\n+ const handleSettingsTitleChange = (event: ChangeEvent) => {\n+ const title = event.target.value;\n+ setDetailFieldset((prev) => ({ ...prev, title }));\n+ setDetailFieldsetChanges((prev) => ({ ...prev, title }));\n+ };\n+\n const handleSettingsDescriptionChange = (event: ChangeEvent) => {\n const description = event.target.value;\n setDetailFieldset((prev) => ({ ...prev, description }));\n@@ -199,6 +212,15 @@ const FieldsetDetails = ({\n const handleSave = (): boolean => {\n if (!fieldset || !isChanged) return false;\n \n+ const titleErrorMessageKey = validateFieldsetTitle(detailFieldset.title);\n+\n+ if (titleErrorMessageKey) {\n+ NotificationManager.warning({\n+ message: formatMessage({ id: titleErrorMessageKey }),\n+ });\n+ return;\n+ }\n+\n if (detailFieldsetChanges.rules) {\n const ruleErrorMessageKey = validateFieldsetRules(detailFieldsetChanges.rules, detailFieldset.fields);\n \n@@ -214,6 +236,9 @@ const FieldsetDetails = ({\n id: fieldset.id,\n };\n \n+ if (detailFieldsetChanges.title !== undefined) {\n+ payload.title = detailFieldsetChanges.title;\n+ }\n if (detailFieldsetChanges.description !== undefined) {\n payload.description = detailFieldsetChanges.description;\n }\n@@ -321,9 +346,42 @@ const FieldsetDetails = ({\n \n \n
\n+
\n+ \n+ \n+
\n+\n
\n \n ({\n ),\n ),\n ),\n+ Tooltip: jest.fn(({ children }) => children),\n RouteLeavingGuard: jest.fn(() => null),\n }));\n ", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/types.ts", "patch": "@@ -10,13 +10,15 @@ export interface IFieldsetDetailsRouteParams {\n export type TFieldsetDetailsProps = RouteComponentProps;\n \n export type TDetailFieldsetState = {\n+ title: string;\n description: string;\n labelPosition: EFieldLabelPosition;\n fields: IExtraField[];\n rules: IFieldsetTemplateRule[];\n };\n \n export type TDetailFieldsetChanges = {\n+ title?: string;\n description?: string;\n labelPosition?: EFieldLabelPosition;\n fields?: IExtraField[];", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/public/components/Fieldsets/FieldsetModal/FieldsetModal.tsx", "patch": "@@ -88,7 +88,7 @@ export function FieldsetModal({ type }: IFieldsetModalProps) {\n if (!validationForm()) return;\n \n if (type === EFieldsetModalType.Create) {\n- dispatch(createFieldsetAction({ name: inputName }));\n+ dispatch(createFieldsetAction({ name: inputName, title: inputName }));\n } else if (currentFieldset) {\n dispatch(updateFieldsetAction({ id: currentFieldset.id, name: inputName }));\n }", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/public/components/Fieldsets/FieldsetModal/__tests__/FieldsetModal.test.tsx", "patch": "@@ -125,7 +125,7 @@ describe('FieldsetModal', () => {\n userEvent.click(submitBtn);\n \n expect(mockDispatch).toHaveBeenCalledWith(\n- createFieldsetAction({ name: 'New FS' }),\n+ createFieldsetAction({ name: 'New FS', title: 'New FS' }),\n );\n expect(mockDispatch).toHaveBeenCalledWith(closeCreateModal());\n expect(mockDispatch).toHaveBeenCalledTimes(2);", "status": "modified"}, {"additions": 174, "deletions": 32, "filename": "frontend/src/public/components/IntegrationsCommon/IntegrationsCommon.css", "patch": "@@ -1,65 +1,207 @@\n .title {\n- margin-bottom: 32px;\n- padding-bottom: 16px;\n+ margin-bottom: 3.2rem;\n+ padding-bottom: 1.6rem;\n width: 100%;\n color: var(--pneumatic-color-black100);\n- border-bottom: 2px solid var(--pneumatic-color-black100);\n+ border-bottom: 0.2rem solid var(--pneumatic-color-black100);\n }\n \n .description {\n- font-size: 15px;\n- line-height: 20px;\n+ font-size: 1.5rem;\n+ line-height: 2rem;\n color: var(--pneumatic-color-black100);\n }\n \n .hint {\n margin: 0;\n- font-size: 13px;\n- line-height: 16px;\n- color: #979795;\n+ font-size: 1.3rem;\n+ line-height: 1.6rem;\n+ color: var(--pneumatic-color-black48);\n }\n \n .link {\n display: inline-block;\n- color: #fec336;\n- transition: all 0.1s ease-in-out;\n+ color: var(--pneumatic-color-link);\n+ transition: color 0.1s ease-in-out;\n \n &:hover {\n- color: #e79a26;\n+ color: var(--pneumatic-color-link-hover);\n+ }\n+\n+ &:focus {\n+ outline: 0.1rem solid var(--pneumatic-color-link);\n+ outline-offset: 0.2rem;\n }\n }\n \n-.api-key {\n- margin: 32px 0;\n+/* API Keys Section */\n+.api-keys {\n+ margin: 3.2rem 0;\n }\n \n-.api-key__title {\n- font-size: 11px;\n+.api-keys__header {\n+ margin-bottom: 1.6rem;\n+ display: flex;\n+ align-items: center;\n+ justify-content: space-between;\n+}\n+\n+.api-keys__title {\n+ margin: 0;\n+ font-size: 1.1rem;\n font-weight: bold;\n letter-spacing: 0.05em;\n text-transform: uppercase;\n- color: #262522;\n+ color: var(--pneumatic-color-black100);\n }\n \n-.api-key__input {\n- margin-bottom: 16px;\n- padding: 0 16px;\n- display: block;\n- width: 100%;\n- height: 40px;\n- line-height: 20px;\n+.api-keys__create-btn {\n+ font-size: 1.3rem;\n+ line-height: 1.6rem;\n+}\n+/* Loading / Empty */\n+.api-keys__loading,\n+.api-keys__empty {\n+ padding: 2.4rem 0;\n+ font-size: 1.4rem;\n+ text-align: center;\n+ color: var(--pneumatic-color-black48);\n+}\n+\n+/* Key List */\n+.api-keys__list {\n+ display: flex;\n+ overflow: hidden;\n+ flex-direction: column;\n+ border: 0.1rem solid var(--pneumatic-color-black16);\n+ border-radius: 0.6rem;\n+ gap: 0;\n+}\n+\n+.api-keys__item {\n+ padding: 1.2rem 1.6rem;\n+ display: flex;\n+ border-bottom: 0.1rem solid var(--pneumatic-color-black8);\n+ align-items: center;\n+ justify-content: space-between;\n+\n+ &:last-child {\n+ border-bottom: none;\n+ }\n+}\n+\n+.api-keys__item-info {\n+ display: flex;\n+ overflow: hidden;\n+ flex-direction: column;\n+ gap: 0.4rem;\n+ min-width: 0;\n+}\n+\n+.api-keys__item-name {\n+ overflow: hidden;\n+ font-size: 1.4rem;\n+ font-weight: 600;\n+ white-space: nowrap;\n+ text-overflow: ellipsis;\n color: var(--pneumatic-color-black100);\n- background-color: var(--background-color);\n- border: 1px solid #dcdcdb;\n- border-radius: 6px;\n- outline: none;\n+}\n \n- &:focus {\n- border-color: #979795;\n+.api-keys__item-prefix {\n+ overflow: hidden;\n+ font-family: monospace;\n+ font-size: 1.3rem;\n+ white-space: nowrap;\n+ letter-spacing: 0.02em;\n+ text-overflow: ellipsis;\n+ color: var(--pneumatic-color-black48);\n+}\n+\n+.api-keys__item-meta {\n+ font-size: 1.2rem;\n+ white-space: nowrap;\n+ color: var(--pneumatic-color-black32);\n+}\n+\n+.api-keys__item-actions {\n+ flex-shrink: 0;\n+ margin-left: 1.6rem;\n+}\n+\n+/* Confirm Delete */\n+.api-keys__confirm-delete {\n+ display: flex;\n+ align-items: center;\n+ gap: 0.8rem;\n+}\n+\n+.api-keys__confirm-text {\n+ max-width: 20rem;\n+ font-size: 1.2rem;\n+ color: var(--pneumatic-color-warning);\n+}\n+\n+/* Create API Key Modal (mirrors CreateGroupModal / tenant-modal) */\n+.create-modal__title {\n+ margin-bottom: 1.6rem;\n+}\n+\n+.create-modal__description {\n+ margin-bottom: 1.6rem;\n+ font-size: 1.5rem;\n+ line-height: 2rem;\n+ color: var(--pneumatic-color-black72);\n+}\n+\n+.create-modal__footer {\n+ margin-top: 3.2rem;\n+ display: flex;\n+\n+ > * + * {\n+ margin-left: 1.6rem;\n }\n }\n \n-.api-key__button {\n- font-size: 13px;\n- line-height: 16px;\n+.api-keys__modal-warning {\n+ margin: 0 0 1.6rem;\n+ padding: 0.8rem 1.2rem;\n+ font-size: 1.4rem;\n+ color: var(--pneumatic-color-warning);\n+ background-color: var(--pneumatic-color-notification1-light);\n+ border-left: 0.3rem solid var(--pneumatic-color-warning);\n+ border-radius: 0.4rem;\n+}\n+\n+.api-keys__modal-key {\n+ margin: 1.6rem 0;\n+ padding: 1.2rem 1.6rem;\n+ display: flex;\n+ align-items: center;\n+ justify-content: space-between;\n+ gap: 1.6rem;\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid var(--pneumatic-color-black16);\n+ border-radius: 0.6rem;\n+}\n+\n+.api-keys__modal-key-value {\n+ font-family: monospace;\n+ font-size: 1.4rem;\n+ word-break: break-all;\n+ color: var(--pneumatic-color-black100);\n+}\n+\n+.api-keys__modal-copy-btn {\n+ padding: 0;\n+ font-size: 1.4rem;\n+ font-weight: 500;\n+ white-space: nowrap;\n+ cursor: pointer;\n+ color: var(--pneumatic-color-link);\n+ background: none;\n+ border: none;\n+}\n+\n+.api-keys__modal-copy-btn:hover {\n+ color: var(--pneumatic-color-link-hover);\n }", "status": "modified"}, {"additions": 191, "deletions": 0, "filename": "frontend/src/public/components/IntegrationsCommon/IntegrationsCommon.test.tsx", "patch": "@@ -0,0 +1,191 @@\n+// \n+import * as React from 'react';\n+import { render, screen } from '@testing-library/react';\n+import userEvent from '@testing-library/user-event';\n+import { useDispatch, useSelector } from 'react-redux';\n+import { intlMock } from '../../__stubs__/intlMock';\n+import { IntegrationsCommon } from './IntegrationsCommon';\n+import {\n+ loadApiKeys,\n+ createApiKey,\n+ deleteApiKey,\n+ clearNewlyCreatedKey,\n+} from '../../redux/actions';\n+import { copyToClipboard } from '../../utils/helpers';\n+\n+\n+\n+jest.mock('../../utils/helpers', () => ({\n+ copyToClipboard: jest.fn(),\n+}));\n+\n+jest.mock('../UI/Buttons/Button', () => ({\n+ Button: ({ label, onClick, 'data-testid': testId, className, type }: any) => (\n+ \n+ ),\n+}));\n+\n+jest.mock('../UI/Fields/InputField', () => ({\n+ InputField: ({ value, onChange, placeholder, 'data-testid': testId, autoFocus }: any) => (\n+ \n+ ),\n+}));\n+\n+jest.mock('../UI/Typeography/Header', () => ({\n+ Header: ({ children, className }: any) => (\n+

{children}

\n+ ),\n+}));\n+\n+jest.mock('../PageTitle/PageTitle', () => ({\n+ PageTitle: () =>
Page Title
,\n+}));\n+\n+describe('IntegrationsCommon', () => {\n+ const mockDispatch = jest.fn();\n+ const t = (id: string) => intlMock.formatMessage({ id });\n+ const TEXT = {\n+ loading: t('integrations.loading-api-key'),\n+ neverUsed: t('integrations.api-key-never-used'),\n+ deleteConfirm: t('integrations.delete-api-key-confirm'),\n+ copied: t('integrations.api-key-copied'),\n+ createBtn: t('integrations.create-api-key'),\n+ doneBtn: t('integrations.api-key-done'),\n+ copyBtn: t('integrations.api-key-copy'),\n+ revokeBtn: t('integrations.api-key-revoke'),\n+ cancelBtn: t('integrations.cancel'),\n+ };\n+\n+ beforeEach(() => {\n+ (useDispatch as unknown as jest.Mock).mockReturnValue(mockDispatch);\n+ (copyToClipboard as jest.Mock).mockClear();\n+ mockDispatch.mockClear();\n+\n+ // Default mock state for useSelector\n+ (useSelector as unknown as jest.Mock).mockImplementation((selectorFn) => {\n+ return selectorFn({\n+ integrations: {\n+ apiKeys: {\n+ data: [],\n+ isLoading: false,\n+ newlyCreatedKey: null,\n+ },\n+ },\n+ });\n+ });\n+ });\n+\n+ afterEach(() => {\n+ jest.clearAllMocks();\n+ });\n+\n+ it('renders loading state correctly', () => {\n+ (useSelector as unknown as jest.Mock).mockImplementation((selectorFn) => {\n+ return selectorFn({\n+ integrations: {\n+ apiKeys: { data: [], isLoading: true, newlyCreatedKey: null },\n+ },\n+ });\n+ });\n+\n+ render();\n+ expect(screen.getByText(TEXT.loading)).toBeInTheDocument();\n+ expect(mockDispatch).toHaveBeenCalledWith(loadApiKeys());\n+ });\n+\n+ it('renders empty state correctly', () => {\n+ render();\n+ expect(screen.getByTestId('empty-keys-message')).toBeInTheDocument();\n+ });\n+\n+ it('renders api keys list', () => {\n+ const mockKeys = [\n+ { id: 1, name: 'Key 1', prefix: 'pn_live_111', lastUsedAt: null },\n+ { id: 2, name: 'Key 2', prefix: 'pn_live_222', lastUsedAt: '2026-07-30T00:00:00Z' },\n+ ];\n+\n+ (useSelector as unknown as jest.Mock).mockImplementation((selectorFn) => {\n+ return selectorFn({\n+ integrations: {\n+ apiKeys: { data: mockKeys, isLoading: false, newlyCreatedKey: null },\n+ },\n+ });\n+ });\n+\n+ render();\n+ \n+ expect(screen.getByTestId('api-keys-list')).toBeInTheDocument();\n+ expect(screen.getByText('Key 1')).toBeInTheDocument();\n+ expect(screen.getByText('pn_live_111••••••••')).toBeInTheDocument();\n+ expect(screen.getByText(TEXT.neverUsed)).toBeInTheDocument();\n+\n+ expect(screen.getByText('Key 2')).toBeInTheDocument();\n+ expect(screen.getByText('pn_live_222••••••••')).toBeInTheDocument();\n+ expect(screen.getByText(/integrations.api-key-last-used/)).toBeInTheDocument();\n+ });\n+\n+ it('handles create api key flow', () => {\n+ render();\n+ \n+ userEvent.click(screen.getByRole('button', { name: TEXT.createBtn }));\n+ expect(screen.getByTestId('create-key-modal')).toBeInTheDocument();\n+\n+ const input = screen.getByTestId('api-key-name-input');\n+ userEvent.type(input, 'New Test Key');\n+\n+ userEvent.click(screen.getByRole('button', { name: TEXT.createBtn }));\n+ expect(mockDispatch).toHaveBeenCalledWith(createApiKey({ name: 'New Test Key' }));\n+ expect(screen.queryByTestId('create-key-modal')).not.toBeInTheDocument();\n+ });\n+\n+ it('handles revoke key flow', () => {\n+ const mockKeys = [{ id: 1, name: 'Key 1', prefix: 'pn_live_111', lastUsedAt: null }];\n+ (useSelector as unknown as jest.Mock).mockImplementation((selectorFn) => {\n+ return selectorFn({\n+ integrations: {\n+ apiKeys: { data: mockKeys, isLoading: false, newlyCreatedKey: null },\n+ },\n+ });\n+ });\n+\n+ render();\n+\n+ // Click revoke (shows confirmation)\n+ userEvent.click(screen.getByRole('button', { name: TEXT.revokeBtn }));\n+ expect(screen.getByText(TEXT.deleteConfirm)).toBeInTheDocument();\n+\n+ // Click confirm revoke\n+ userEvent.click(screen.getByRole('button', { name: TEXT.revokeBtn }));\n+ expect(mockDispatch).toHaveBeenCalledWith(deleteApiKey({ id: 1 }));\n+ });\n+\n+ it('displays newly created key modal and handles copy', () => {\n+ (useSelector as unknown as jest.Mock).mockImplementation((selectorFn) => {\n+ return selectorFn({\n+ integrations: {\n+ apiKeys: { data: [], isLoading: false, newlyCreatedKey: 'pn_live_secret_key_abc' },\n+ },\n+ });\n+ });\n+\n+ render();\n+ \n+ expect(screen.getByTestId('new-key-modal')).toBeInTheDocument();\n+ expect(screen.getByTestId('raw-key-value')).toHaveTextContent('pn_live_secret_key_abc');\n+\n+ userEvent.click(screen.getByRole('button', { name: TEXT.copyBtn }));\n+ expect(copyToClipboard).toHaveBeenCalledWith('pn_live_secret_key_abc');\n+ expect(screen.getByRole('button', { name: TEXT.copied })).toBeInTheDocument();\n+\n+ userEvent.click(screen.getByRole('button', { name: TEXT.doneBtn }));\n+ expect(mockDispatch).toHaveBeenCalledWith(clearNewlyCreatedKey());\n+ });\n+});", "status": "added"}, {"additions": 278, "deletions": 32, "filename": "frontend/src/public/components/IntegrationsCommon/IntegrationsCommon.tsx", "patch": "@@ -1,61 +1,307 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n import * as React from 'react';\n-import { useIntl } from 'react-intl';\n+import { useIntl, FormattedDate } from 'react-intl';\n+import { useDispatch, useSelector } from 'react-redux';\n \n+import { IApiKeyItem } from '../../types/integrations';\n+import { IApplicationState } from '../../types/redux';\n import { copyToClipboard } from '../../utils/helpers';\n-import { NotificationManager } from '../UI/Notifications';\n import { Button } from '../UI/Buttons/Button';\n-\n-import styles from './IntegrationsCommon.css';\n+import { InputField } from '../UI/Fields/InputField';\n+import { Header } from '../UI/Typeography/Header';\n+import { Modal } from '../UI/Modal/Modal';\n+import { NotificationManager } from '../UI/Notifications';\n import { EPageTitle } from '../../constants/defaultValues';\n import { PageTitle } from '../PageTitle/PageTitle';\n+import {\n+ loadApiKeys,\n+ createApiKey,\n+ deleteApiKey,\n+ clearNewlyCreatedKey,\n+} from '../../redux/actions';\n+\n+import styles from './IntegrationsCommon.css';\n+\n+const KEY_MASK = '••••••••';\n \n-export interface IIntegrationsCommonProps {\n- apiKey: string;\n- isApiKeyLoading: boolean;\n- loadApiKey(): void;\n+interface IApiKeyListItemProps {\n+ apiKey: IApiKeyItem;\n+ onRevoke: (id: number) => void;\n }\n \n-export function IntegrationsCommon({ apiKey, isApiKeyLoading, loadApiKey }: IIntegrationsCommonProps) {\n+const ApiKeyListItem = React.memo(({\n+ apiKey,\n+ onRevoke,\n+}: IApiKeyListItemProps) => {\n+ const { formatMessage } = useIntl();\n+\n+ const handleRevoke = React.useCallback(() => {\n+ onRevoke(apiKey.id);\n+ }, [apiKey.id, onRevoke]);\n+\n+ return (\n+
\n+
\n+ {apiKey.name}\n+ \n+ {apiKey.prefix}{KEY_MASK}\n+ \n+ \n+ {apiKey.lastUsedAt\n+ ? formatMessage(\n+ { id: 'integrations.api-key-last-used' },\n+ { date: },\n+ )\n+ : formatMessage({ id: 'integrations.api-key-never-used' })\n+ }\n+ \n+
\n+
\n+ \n+
\n+
\n+ );\n+});\n+ApiKeyListItem.displayName = 'ApiKeyListItem';\n+\n+export function IntegrationsCommon() {\n+ const { formatMessage } = useIntl();\n+ const dispatch = useDispatch();\n+\n+ const apiKeys = useSelector(\n+ (state: IApplicationState) => state.integrations.apiKeys.data,\n+ );\n+ const isLoading = useSelector(\n+ (state: IApplicationState) => state.integrations.apiKeys.isLoading,\n+ );\n+ const newlyCreatedKey = useSelector(\n+ (state: IApplicationState) => state.integrations.apiKeys.newlyCreatedKey,\n+ );\n+\n+ const [confirmDeleteId, setConfirmDeleteId] = React.useState(null);\n+ const [newKeyName, setNewKeyName] = React.useState('');\n+ const [showCreateForm, setShowCreateForm] = React.useState(false);\n+\n React.useEffect(() => {\n- loadApiKey();\n+ dispatch(loadApiKeys());\n+\n+ return () => {\n+ dispatch(clearNewlyCreatedKey());\n+ };\n+ }, [dispatch]);\n+\n+ const handleCreate = React.useCallback(() => {\n+ dispatch(createApiKey({ name: newKeyName || undefined }));\n+ setNewKeyName('');\n+ setShowCreateForm(false);\n+ }, [newKeyName, dispatch]);\n+\n+ const handleCreateSubmit = React.useCallback(\n+ (e: React.FormEvent) => {\n+ e.preventDefault();\n+ handleCreate();\n+ },\n+ [handleCreate],\n+ );\n+\n+ const handleDelete = React.useCallback(() => {\n+ if (confirmDeleteId !== null) {\n+ dispatch(deleteApiKey({ id: confirmDeleteId }));\n+ setConfirmDeleteId(null);\n+ }\n+ }, [confirmDeleteId, dispatch]);\n+\n+ const handleConfirmDeleteStart = React.useCallback((id: number) => {\n+ setConfirmDeleteId(id);\n }, []);\n \n- const { formatMessage } = useIntl();\n- const apiKeyValue = isApiKeyLoading ? formatMessage({ id: 'integrations.loading-api-key' }) : apiKey;\n+ const handleConfirmDeleteCancel = React.useCallback(() => {\n+ setConfirmDeleteId(null);\n+ }, []);\n+\n+ const handleCloseNewKeyModal = React.useCallback(() => {\n+ dispatch(clearNewlyCreatedKey());\n+ }, [dispatch]);\n+\n+ const handleShowCreateForm = React.useCallback(() => {\n+ setShowCreateForm(true);\n+ }, []);\n+\n+ const handleHideCreateForm = React.useCallback(() => {\n+ setShowCreateForm(false);\n+ setNewKeyName('');\n+ }, []);\n \n- const handleCopyKey = () => {\n- if (!apiKey) {\n- return;\n+ const handleCopyNewlyCreatedKey = React.useCallback(() => {\n+ if (newlyCreatedKey) {\n+ copyToClipboard(newlyCreatedKey);\n+ NotificationManager.success({ message: 'integrations.api-key-copied' });\n }\n+ }, [newlyCreatedKey]);\n \n- copyToClipboard(apiKey);\n- NotificationManager.success({ message: 'user.copied-to-clipboard' });\n- };\n+ const handleNameChange = React.useCallback(\n+ (e: React.ChangeEvent) => {\n+ setNewKeyName(e.target.value);\n+ },\n+ [],\n+ );\n \n const supportEmail = formatMessage({ id: 'integrations.support-email' });\n+ const supportEmailLink = `mailto:${supportEmail}`;\n \n return (\n <>\n \n-

{formatMessage({ id: 'integrations.description' })}

\n+

\n+ {formatMessage({ id: 'integrations.description' })}\n+

\n \n-
\n-

{formatMessage({ id: 'integrations.api-key-title' })}

\n- \n- \n+
\n+
\n+

\n+ {formatMessage({ id: 'integrations.api-keys-title' })}\n+

\n+ \n+
\n+\n+ {isLoading && (\n+

\n+ {formatMessage({ id: 'integrations.loading-api-key' })}\n+

\n+ )}\n+\n+ {!isLoading && apiKeys.length === 0 && (\n+

\n+ {formatMessage({ id: 'integrations.no-api-keys' })}\n+

\n+ )}\n+\n+ {!isLoading && apiKeys.length > 0 && (\n+
\n+ {apiKeys.map((key: IApiKeyItem) => (\n+ \n+ ))}\n+
\n+ )}\n
\n \n+ {/* Newly created key modal */}\n+ \n+
\n+
\n+ {formatMessage({ id: 'integrations.api-key-created-title' })}\n+
\n+

\n+ {formatMessage({ id: 'integrations.api-key-created-warning' })}\n+

\n+
\n+ \n+ {newlyCreatedKey}\n+ \n+ \n+ {formatMessage({ id: 'team.create-user-modal.copy' })}\n+ \n+
\n+
\n+ \n+
\n+
\n+
\n+\n+ {/* Revoke confirmation modal */}\n+ \n+
\n+
\n+ {formatMessage({ id: 'integrations.revoke-modal-title' })}\n+
\n+

\n+ {formatMessage({ id: 'integrations.delete-api-key-confirm' })}\n+

\n+
\n+ \n+ \n+
\n+
\n+
\n+\n+ {/* Create API Key modal */}\n+ \n+
\n+
\n+ {formatMessage({ id: 'integrations.create-api-key-modal-title' })}\n+
\n+

\n+ {formatMessage({ id: 'integrations.create-api-key-modal-description' })}\n+

\n+
\n+ \n+
\n+ \n+ \n+
\n+ \n+
\n+
\n+\n

\n {formatMessage({ id: 'integrations.hint' })}\n- {supportEmail}\n+ {supportEmail}\n

\n \n );", "status": "modified"}, {"additions": 8, "deletions": 21, "filename": "frontend/src/public/components/IntegrationsCommon/container.tsx", "patch": "@@ -1,21 +1,8 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n-import { connect } from 'react-redux';\n-import { loadApiKey } from '../../redux/actions';\n-import { IApplicationState } from '../../types/redux';\n-import { IntegrationsCommon, IIntegrationsCommonProps } from './IntegrationsCommon';\n-\n-type TIntegrationsCommonStoreProps = Pick;\n-type TIntegrationsCommonDispatchProps = Pick;\n-\n-function mapStateToProps({ integrations: { apiKey } }: IApplicationState): TIntegrationsCommonStoreProps {\n-\n- return {\n- apiKey: apiKey.data,\n- isApiKeyLoading: apiKey.isLoading,\n- };\n-}\n-\n-const mapDispatchToProps: TIntegrationsCommonDispatchProps = { loadApiKey };\n-\n-export const IntegrationsCommonContainer = connect(mapStateToProps, mapDispatchToProps)(IntegrationsCommon);\n+import { IntegrationsCommon } from './IntegrationsCommon';\n+\n+/**\n+ * @deprecated Use IntegrationsCommon directly — it uses\n+ * useSelector/useDispatch internally. This alias exists\n+ * for backward compatibility with existing imports.\n+ */\n+export const IntegrationsCommonContainer = IntegrationsCommon;", "status": "modified"}, {"additions": 0, "deletions": 2, "filename": "frontend/src/public/components/IntegrationsCommon/index.ts", "patch": "@@ -1,4 +1,2 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n export * from './IntegrationsCommon';\n export * from './container';", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/KickoffEdit/KickoffEdit.tsx", "patch": "@@ -2,7 +2,7 @@ import * as React from 'react';\n import { useEffect } from 'react';\n import classnames from 'classnames';\n import { useIntl } from 'react-intl';\n-import { IExtraField, IKickoffClient } from '../../types/template';\n+import { IExtraField, IRuntimeKickoffClient } from '../../types/template';\n import { IFieldsetRuntime } from '../../types/fieldset';\n import { EInputNameBackgroundColor } from '../../types/workflow';\n import { isArrayWithItems } from '../../utils/helpers';\n@@ -17,7 +17,7 @@ import { Button } from '../UI/Buttons/Button';\n import styles from './KickoffEdit.css';\n \n export interface IEditKickoffProps {\n- kickoff: IKickoffClient | null;\n+ kickoff: IRuntimeKickoffClient | null;\n fieldsets?: IFieldsetRuntime[];\n isLoading?: boolean;\n accountId: number;", "status": "modified"}, {"additions": 4, "deletions": 0, "filename": "frontend/src/public/components/KickoffOutputs/KickoffOutputs.css", "patch": "@@ -96,6 +96,8 @@\n font-weight: bold;\n line-height: 20px;\n color: #262522;\n+\n+ @mixin text-wrap;\n }\n \n .fieldset-output-group__description {\n@@ -104,4 +106,6 @@\n font-size: 13px;\n line-height: 18px;\n color: #79756d;\n+\n+ @mixin text-wrap;\n }", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/public/components/KickoffOutputs/KickoffOutputs.tsx", "patch": "@@ -102,7 +102,7 @@ export function KickoffOutputs({\n \n const renderFieldsetGroup = (fieldset: IFieldsetRuntime, children: React.ReactNode, key?: string) => (\n
\n- {fieldset.name &&

{fieldset.name}

}\n+

{fieldset.title}

\n {fieldset.description &&

{fieldset.description}

}\n {children}\n
", "status": "modified"}, {"additions": 7, "deletions": 3, "filename": "frontend/src/public/components/KickoffOutputs/__tests__/KickoffOutputs.test.tsx", "patch": "@@ -92,9 +92,10 @@ describe('KickoffOutputs', () => {\n ]);\n });\n \n- it('in full mode renders fieldset group: name, description and only non-empty fields', () => {\n+ it('in full mode renders fieldset group: title, description and only non-empty fields', () => {\n const fieldset = makeFieldsetRuntime({\n- name: 'Contacts',\n+ name: 'Tech Catalog Name',\n+ title: 'User Contacts Title',\n description: 'Reachout details',\n order: 1,\n fields: [\n@@ -110,7 +111,8 @@ describe('KickoffOutputs', () => {\n fieldsets: [fieldset],\n }));\n \n- expect(screen.getByText('Contacts')).toBeInTheDocument();\n+ expect(screen.getByText('User Contacts Title')).toBeInTheDocument();\n+ expect(screen.queryByText('Tech Catalog Name')).not.toBeInTheDocument();\n expect(screen.getByText('Reachout details')).toBeInTheDocument();\n \n expect(screen.getByTestId('text-output-email')).toBeInTheDocument();\n@@ -129,6 +131,7 @@ describe('KickoffOutputs', () => {\n \n const fieldset = makeFieldsetRuntime({\n name: 'Docs',\n+ title: 'Docs',\n fields: [fileField],\n });\n \n@@ -144,6 +147,7 @@ describe('KickoffOutputs', () => {\n it('in truncated mode renders fieldset group title and only the first field', () => {\n const fieldset = makeFieldsetRuntime({\n name: 'Profile',\n+ title: 'Profile',\n order: 5,\n fields: [\n makeExtraField({ apiName: 'first', name: 'First', value: 'one' }),", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/MergedOutputList/MergedOutputList.tsx", "patch": "@@ -49,7 +49,7 @@ export function MergedOutputList({\n if (mergedOutput.kind === 'fieldset') {\n const {\n apiNameBinding: fieldsetApiName,\n- name: fieldsetName,\n+ title: fieldsetTitle,\n description: fieldsetDescription,\n fields: fieldsetFields,\n labelPosition: fieldsetLabelPosition,\n@@ -58,7 +58,7 @@ export function MergedOutputList({\n return (\n {\n makeExtraField({ apiName: 'field-a', name: 'field-a', order: 1 }),\n makeExtraField({ apiName: 'field-b', name: 'field-b', order: 3 }),\n ];\n- const fieldsets = [makeFieldsetRuntime({ apiNameBinding: 'fs-10', name: 'Fieldset Middle', order: 2 })];\n+ const fieldsets = [\n+ makeFieldsetRuntime({\n+ apiNameBinding: 'fs-10',\n+ name: 'Fieldset Middle Catalog Name',\n+ title: 'Fieldset Middle Title',\n+ order: 2,\n+ }),\n+ ];\n \n const { container } = render(\n ,\n@@ -47,7 +54,7 @@ describe('MergedOutputList', () => {\n expect(items).toHaveLength(3);\n \n expect(items[0].textContent).toBe('field-b');\n- expect(items[1].textContent).toBe('Fieldset Middle');\n+ expect(items[1].textContent).toBe('Fieldset Middle Title');\n expect(items[2].textContent).toBe('field-a');\n });\n \n@@ -61,7 +68,12 @@ describe('MergedOutputList', () => {\n });\n \n it('renders only fieldsets when fields array is empty', () => {\n- const fieldsets = [makeFieldsetRuntime({ name: 'Only FS' })];\n+ const fieldsets = [\n+ makeFieldsetRuntime({\n+ name: 'Only FS Catalog Name',\n+ title: 'Only FS Title',\n+ }),\n+ ];\n \n render();\n ", "status": "modified"}, {"additions": 2, "deletions": 5, "filename": "frontend/src/public/components/PublicFormsApp/common/types.ts", "patch": "@@ -1,9 +1,6 @@\n-import { IKickoffClient } from '../../../types/template';\n-import { IFieldsetRuntime } from '../../../types/fieldset';\n+import { IRuntimeKickoffClient } from '../../../types/template';\n \n-export interface IPublicFormKickoff extends Omit {\n- fieldsets: IFieldsetRuntime[];\n-}\n+export type IPublicFormKickoff = IRuntimeKickoffClient;\n \n export interface IPublicForm {\n accountId: number;", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/Integrations/TemplateIntegrations.tsx", "patch": "@@ -10,7 +10,7 @@ import { TemplateIntegrationsMenu } from './Menu';\n import { ZAPIER_EMBED_CSS_HREF, ZAPIER_EMBED_SCRIPT_SRC } from '../../../constants/defaultValues';\n import { useLink } from '../../../hooks/useLink';\n import { useScript } from '../../../hooks/useScript';\n-import { loadApiKey, loadWebhooks } from '../../../redux/actions';\n+import { loadApiKeys, loadWebhooks } from '../../../redux/actions';\n import { getTemplateData } from '../../../redux/selectors/template';\n import { getUserApiKey } from '../../../redux/selectors/user';\n import { copyToClipboard } from '../../../utils/helpers';\n@@ -131,7 +131,7 @@ export function TemplateIntegrations() {\n \n useEffect(() => {\n if (isExpanded) {\n- dispatch(loadApiKey());\n+ dispatch(loadApiKeys());\n dispatch(loadWebhooks());\n }\n }, [isExpanded]);", "status": "modified"}, {"additions": 11, "deletions": 3, "filename": "frontend/src/public/components/TemplateEdit/KickoffRedux/KickoffRedux.tsx", "patch": "@@ -20,7 +20,7 @@ import { MergedOutputRows } from '../TaskOutputFlow/MergedOutputRows';\n \n import { KickoffMenu } from './KickoffMenu';\n import { IntlMessages } from '../../IntlMessages';\n-import { EExtraFieldType, IExtraField, ETemplateParts, IKickoffClient, ITemplateClient } from '../../../types/template';\n+import { EExtraFieldType, IExtraField, ETemplateParts, ITemplateKickoffClient, ITemplateClient } from '../../../types/template';\n import { IFieldsetCatalogItem } from '../../../types/fieldset';\n import { isArrayWithItems } from '../../../utils/helpers';\n import { ExtraFieldsMap } from '../ExtraFields/utils/ExtraFieldsMap';\n@@ -44,7 +44,7 @@ export interface IKickoffReduxProps {\n intl: IntlShape;\n accountId: number;\n templateStatus: ETemplateStatus;\n- setKickoff(value: IKickoffClient): void;\n+ setKickoff(value: ITemplateKickoffClient): void;\n }\n \n export function KickoffRedux({\n@@ -84,7 +84,7 @@ export function KickoffRedux({\n setIsOpen(!isOpen);\n };\n \n- const handleChangeKickoff = (newKickoff: IKickoffClient) => {\n+ const handleChangeKickoff = (newKickoff: ITemplateKickoffClient) => {\n setKickoff(newKickoff);\n };\n \n@@ -131,6 +131,13 @@ export function KickoffRedux({\n saveOutputOrders(moved);\n };\n \n+ const handleEditFieldsetTitle = (apiNameBinding: string, title: string) => {\n+ const nextFieldsets = (kickoff.fieldsets || []).map((fieldset) =>\n+ fieldset.apiNameBinding === apiNameBinding ? { ...fieldset, title } : fieldset,\n+ );\n+ handleChangeKickoff({ ...kickoff, fieldsets: nextFieldsets });\n+ };\n+\n const renderKickoffForm = () => {\n const isFormEmpty = !isArrayWithItems(kickoff.fields) && !(kickoff.fieldsets || []).length && !kickoff.description;\n \n@@ -182,6 +189,7 @@ export function KickoffRedux({\n datasetOptions={datasetOptions}\n accountId={accountId}\n formatMessage={formatMessage}\n+ onEditFieldsetTitle={handleEditFieldsetTitle}\n />\n
\n )}", "status": "modified"}, {"additions": 4, "deletions": 4, "filename": "frontend/src/public/components/TemplateEdit/KickoffRedux/__tests__/KickoffRedux.test.tsx", "patch": "@@ -7,7 +7,7 @@ import { makeExtraField } from '../../../../__stubs__/fields.factory';\n import { makeFieldsetBindingClient, makeFieldsetField } from '../../../../__stubs__/fieldsets.factory';\n import {\n IExtraField,\n- IKickoffClient,\n+ ITemplateKickoffClient,\n ITemplateClient,\n } from '../../../../types/template';\n import { IFieldsetCatalogItem } from '../../../../types/fieldset';\n@@ -176,14 +176,14 @@ describe('KickoffRedux', () => {\n ...overrides,\n });\n \n- const makeKickoff = (overrides: Partial = {}): IKickoffClient => ({\n+ const makeKickoff = (overrides: Partial = {}): ITemplateKickoffClient => ({\n description: '',\n fields: [],\n fieldsets: [],\n ...overrides,\n });\n \n- const makeTemplate = (kickoff: IKickoffClient): ITemplateClient => ({\n+ const makeTemplate = (kickoff: ITemplateKickoffClient): ITemplateClient => ({\n id: 1,\n kickoff,\n wfNameTemplate: '',\n@@ -196,7 +196,7 @@ describe('KickoffRedux', () => {\n });\n \n const renderKickoff = (params: {\n- kickoff: IKickoffClient;\n+ kickoff: ITemplateKickoffClient;\n setKickoff?: jest.Mock;\n }) => {\n const setKickoff = params.setKickoff ?? jest.fn();", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/KickoffRedux/utils/isKickoffCleared.ts", "patch": "@@ -1,9 +1,9 @@\n /* eslint-disable */\n /* prettier-ignore */\n-import { IKickoffClient } from '../../../../types/template';\n+import { ITemplateKickoffClient } from '../../../../types/template';\n import { isArrayWithItems } from '../../../../utils/helpers';\n \n-export const isKickoffCleared = (kickoff: IKickoffClient) => {\n+export const isKickoffCleared = (kickoff: ITemplateKickoffClient) => {\n const hasFields = isArrayWithItems(kickoff.fields);\n \n return !hasFields && !kickoff.description;", "status": "modified"}, {"additions": 34, "deletions": 1, "filename": "frontend/src/public/components/TemplateEdit/OutputForm/OutputForm.css", "patch": "@@ -75,6 +75,39 @@\n margin-top: 0.5rem;\n }\n \n-.flow__fieldset-name {\n+.flow__fieldset-header {\n+ color: var(--pneumatic-color-black100);\n+}\n+\n+.flow__fieldset-label {\n+ font-weight: 600;\n+ color: var(--pneumatic-color-black48);\n+}\n+\n+.flow__fieldset-title-edit {\n+ display: inline-flex;\n+ align-items: center;\n+ margin-top: 0.2rem;\n+ padding-left: 1.2rem;\n+ gap: 0.4rem;\n+\n @mixin text-small;\n }\n+\n+.flow__fieldset-title-input {\n+ border: none;\n+ resize: none;\n+ outline: none;\n+ field-sizing: content;\n+\n+ &::placeholder {\n+ color: var(--default-placeholder-color);\n+ }\n+}\n+\n+.flow__fieldset-title-edit_error {\n+ & .flow__fieldset-title-input::placeholder {\n+ color: var(--pneumatic-color-warning);\n+ }\n+}\n+", "status": "modified"}, {"additions": 11, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/OutputForm/OutputFormTaskMerged.tsx", "patch": "@@ -131,6 +131,16 @@ export function OutputFormTaskMerged({\n [saveOutputOrders, task.fieldsets, task.fields],\n );\n \n+ const handleEditFieldsetTitle = useCallback(\n+ (apiNameBinding: string, title: string) => {\n+ const nextFieldsets = (task.fieldsets || []).map((fieldset) =>\n+ fieldset.apiNameBinding === apiNameBinding ? { ...fieldset, title } : fieldset,\n+ );\n+ patchTask({ taskUUID: task.uuid, changedFields: { fieldsets: nextFieldsets } });\n+ },\n+ [patchTask, task.fieldsets, task.uuid],\n+ );\n+\n \n const isEmpty = !isArrayWithItems(task.fields) && !(task.fieldsets || []).length;\n \n@@ -160,6 +170,7 @@ export function OutputFormTaskMerged({\n accountId={accountId}\n formatMessage={formatMessage}\n innerRef={outputRef}\n+ onEditFieldsetTitle={handleEditFieldsetTitle}\n />\n
\n )}", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/DueDate/DueDate.tsx", "patch": "@@ -5,7 +5,7 @@ import classnames from 'classnames';\n import { DropdownList, Duration } from '../../../UI';\n import { TrashIcon } from '../../../icons';\n \n-import { IDueDate, IKickoffClient, ITemplateTaskClient } from '../../../../types/template';\n+import { IDueDate, ITemplateKickoffClient, ITemplateTaskClient } from '../../../../types/template';\n import { START_DURATION } from '../../constants';\n import { getRuleTargetOptions, TRuleTargetOption } from './utils/getRuleTargetOptions';\n import { getRulePrepositionOptions, TRulePrepositionOption } from './utils/getRulePrepositionOptions';\n@@ -17,7 +17,7 @@ import stylesTaskForm from '../TaskForm.css';\n interface IDueInProps {\n currentTask: ITemplateTaskClient;\n tasks: ITemplateTaskClient[];\n- kickoff: IKickoffClient;\n+ kickoff: ITemplateKickoffClient;\n onChange(value: IDueDate): void;\n dueDate: ITemplateTaskClient['rawDueDate'];\n }", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/DueDate/utils/__tests__/getRuleTargetOptions.test.ts", "patch": "@@ -1,4 +1,4 @@\n-import { EExtraFieldType, IKickoffClient, ITemplateTaskClient } from '../../../../../../types/template';\n+import { EExtraFieldType, ITemplateKickoffClient, ITemplateTaskClient } from '../../../../../../types/template';\n import { makeFieldsetField, makeFieldsetBindingClient } from '../../../../../../__stubs__/fieldsets.factory';\n import { createEmptyTaskDueDate } from '../../../../../../utils/dueDate/createEmptyTaskDueDate';\n import { getRuleTargetOptions } from '../getRuleTargetOptions';\n@@ -28,7 +28,7 @@ const makeTask = (overrides: Partial = {}): ITemplateTaskCl\n ...overrides,\n });\n \n-const makeKickoff = (overrides: Partial = {}): IKickoffClient => ({\n+const makeKickoff = (overrides: Partial = {}): ITemplateKickoffClient => ({\n description: '',\n fields: [],\n fieldsets: [],", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/DueDate/utils/getRuleTargetOptions.ts", "patch": "@@ -1,6 +1,6 @@\n import {\n EExtraFieldType,\n- IKickoffClient,\n+ ITemplateKickoffClient,\n ITemplateTaskClient,\n TDueDateRuleTarget,\n } from '../../../../../types/template';\n@@ -16,7 +16,7 @@ export type TRuleTargetOption = TDropdownOptionBase & {\n export function getRuleTargetOptions(\n currentTask: ITemplateTaskClient,\n tasks: ITemplateTaskClient[],\n- kickoff: IKickoffClient,\n+ kickoff: ITemplateKickoffClient,\n ): readonly [TRuleTargetOption[], TRuleTargetOption[], TRuleTargetOption[]] {\n const prevTasks = getPreviousTasks(currentTask, tasks);\n const prevDateVariables = getTaskVariables(kickoff, tasks, currentTask).filter(", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/TaskForm.tsx", "patch": "@@ -6,7 +6,7 @@ import { useSelector } from 'react-redux';\n import { TaskDescriptionEditor } from './TaskDescriptionEditor';\n import { scrollToElement } from '../../../utils/helpers';\n import { TUserListItem } from '../../../types/user';\n-import { IKickoffClient, ITemplateTaskClient } from '../../../types/template';\n+import { ITemplateKickoffClient, ITemplateTaskClient } from '../../../types/template';\n import { TTaskVariable, TTaskFormPart, ETaskFormParts } from '../types';\n import { OutputFormIntl } from '../OutputForm/OutputForm';\n import { ShowMore } from '../../UI/ShowMore';\n@@ -38,7 +38,7 @@ export interface ITaskFormProps {\n accountId: number;\n isTeamInvitesModalOpen: boolean;\n tasks: ITemplateTaskClient[];\n- kickoff: IKickoffClient;\n+ kickoff: ITemplateKickoffClient;\n patchTask(args: TPatchTaskPayload): void;\n }\n ", "status": "modified"}, {"additions": 5, "deletions": 5, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/utils/__tests__/getTaskVariables.test.ts", "patch": "@@ -1,7 +1,7 @@\n import { createElement } from 'react';\n import { render, screen } from '@testing-library/react';\n \n-import { EExtraFieldType, IKickoffClient, ITemplateTaskClient } from '../../../../../types/template';\n+import { EExtraFieldType, ITemplateKickoffClient, ITemplateTaskClient } from '../../../../../types/template';\n import { IFieldsetRuntime } from '../../../../../types/fieldset';\n import { makeExtraField } from '../../../../../__stubs__/fields.factory';\n import { makeFieldsetRuntime, makeFieldsetBindingClient, makeFieldsetField } from '../../../../../__stubs__/fieldsets.factory';\n@@ -20,7 +20,7 @@ import {\n SYSTEM_VARIABLE_SUBTITLE,\n } from '../getTaskVariables';\n \n-const mockKikoff: IKickoffClient = {\n+const mockKikoff: ITemplateKickoffClient = {\n description: 'Kickoff description',\n fields: [\n makeExtraField({\n@@ -223,7 +223,7 @@ describe('getTaskVariables', () => {\n \n describe('getKickoffVariables with fieldsets', () => {\n it('adds kickoff fieldset fields after regular kickoff fields', () => {\n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n ...mockKikoff,\n fieldsets: [makeFieldsetBindingClient({\n apiNameBinding: mockFieldsetData.apiNameBinding,\n@@ -242,7 +242,7 @@ describe('getKickoffVariables with fieldsets', () => {\n });\n \n it('skips fieldset missing from catalog without crashing or producing phantom options', () => {\n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n ...mockKikoff,\n fieldsets: [\n makeFieldsetBindingClient({ apiNameBinding: 'missing-fs' }),\n@@ -379,7 +379,7 @@ describe('useWorkflowNameVariables', () => {\n \n it('includes 4 system variables plus single-line kickoff and fieldset fields, filters out multi-line types', () => {\n \n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n description: '',\n fields: [\n makeExtraField({", "status": "modified"}, {"additions": 6, "deletions": 5, "filename": "frontend/src/public/components/TemplateEdit/TaskForm/utils/getTaskVariables.tsx", "patch": "@@ -4,7 +4,8 @@ import { useMemo } from 'react';\n import { useIntl } from 'react-intl';\n \n import {\n- IKickoffClient,\n+ ITemplateKickoffClient,\n+ IRuntimeKickoffClient,\n IExtraField,\n ITemplateTaskClient,\n IFieldsetBindingClient,\n@@ -46,7 +47,7 @@ export function getLocalizedSystemVariable({\n }\n \n type TGetVariablesParam = {\n- kickoff: Pick & { fieldsets?: (IFieldsetBindingClient | TTemplateFieldFieldset)[] };\n+ kickoff: Pick & { fieldsets?: (IFieldsetBindingClient | TTemplateFieldFieldset)[] };\n tasks: (Pick & {\n name?: ITemplateTaskClient['name'];\n fieldsets?: (IFieldsetBindingClient | TTemplateFieldFieldset)[];\n@@ -131,7 +132,7 @@ export function getVariables(params: TGetVariablesParam): TTaskVariable[] {\n }\n \n export function getKickoffVariables(\n- kickoff?: Pick & { fieldsets?: (IFieldsetBindingClient | TTemplateFieldFieldset)[] },\n+ kickoff?: Pick & { fieldsets?: (IFieldsetBindingClient | TTemplateFieldFieldset)[] },\n ) {\n const fromFields = kickoff?.fields.map((field) => getVariableFromField(field, 'Kick-off form')) ?? [];\n const fromFieldsets = getVariablesFromSelectedFieldsets(\n@@ -144,7 +145,7 @@ export function getKickoffVariables(\n }\n \n export function getTaskVariables(\n- kickoff: IKickoffClient,\n+ kickoff: ITemplateKickoffClient,\n tasks: ITemplateTaskClient[],\n currentTask: ITemplateTaskClient,\n templateId?: number,\n@@ -189,7 +190,7 @@ export const getSingleLineVariables = (variables: TTaskVariable[]) => {\n };\n \n export const useWorkflowNameVariables = (\n- kickoff?: Pick,\n+ kickoff?: Pick,\n ) => {\n const { formatMessage } = useIntl();\n ", "status": "modified"}, {"additions": 70, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/FieldsetEditorTitle.tsx", "patch": "@@ -0,0 +1,70 @@\n+import * as React from 'react';\n+import { useState, useRef, useEffect } from 'react';\n+import classnames from 'classnames';\n+\n+import { PencilSmallIcon } from '../../icons';\n+import { validateFieldsetTitle } from '../../../utils/validators';\n+\n+import styles from '../OutputForm/OutputForm.css';\n+import kickoffStyles from '../KickoffRedux/KickoffRedux.css';\n+\n+import { IFieldsetEditorTitleProps } from './types';\n+\n+export function FieldsetEditorTitle({\n+ apiNameBinding,\n+ title,\n+ onEditFieldsetTitle,\n+ formatMessage,\n+}: IFieldsetEditorTitleProps) {\n+ const [localTitle, setLocalTitle] = useState(title);\n+ const [isFocused, setIsFocused] = useState(false);\n+ const inputRef = useRef(null);\n+\n+ useEffect(() => {\n+ setLocalTitle(title);\n+ }, [title]);\n+\n+ const isTitleError = Boolean(validateFieldsetTitle(localTitle));\n+\n+ const handleBlur = () => {\n+ setIsFocused(false);\n+ if (localTitle !== title) {\n+ onEditFieldsetTitle(apiNameBinding, localTitle);\n+ }\n+ };\n+\n+ return (\n+ \n+ {formatMessage({ id: 'fieldsets.title-label' })}:\n+ setLocalTitle(event.target.value)}\n+ placeholder={formatMessage({ id: 'fieldsets.settings.title-placeholder' })}\n+ rows={1}\n+ onFocus={() => setIsFocused(true)}\n+ onBlur={handleBlur}\n+ onKeyDown={(event) => {\n+ if (event.key === 'Enter') {\n+ event.preventDefault();\n+ event.currentTarget.blur();\n+ }\n+ }}\n+ />\n+ {!isFocused && (\n+ inputRef.current?.focus()}\n+ className={kickoffStyles['kick-off-edit-name']}\n+ >\n+ \n+ \n+ )}\n+
\n+ );\n+}", "status": "added"}, {"additions": 13, "deletions": 8, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/MergedOutputRows.tsx", "patch": "@@ -9,6 +9,7 @@ import { isArrayWithItems } from '../../../utils/helpers';\n import { ExtraFieldIntl } from '../ExtraFields';\n import { ExtraFieldsLabels } from '../ExtraFields/utils/ExtraFieldsLabels';\n import { FieldsetFlowRowDropdown } from './FieldsetFlowRowDropdown';\n+import { FieldsetEditorTitle } from './FieldsetEditorTitle';\n import { TMergedTaskOutputRow } from './mergeTaskOutputFlow';\n \n import styles from '../OutputForm/OutputForm.css';\n@@ -24,6 +25,7 @@ export interface IMergedOutputRowsProps {\n accountId: number;\n formatMessage: (descriptor: { id: string }) => string;\n innerRef?: React.RefObject;\n+ onEditFieldsetTitle: (apiNameBinding: string, title: string) => void;\n }\n \n export function MergedOutputRows({\n@@ -36,6 +38,7 @@ export function MergedOutputRows({\n accountId,\n formatMessage,\n innerRef,\n+ onEditFieldsetTitle,\n }: IMergedOutputRowsProps) {\n return (\n <>\n@@ -64,8 +67,7 @@ export function MergedOutputRows({\n />\n );\n }\n- const { name, fields, apiNameBinding } = mapFieldsetBindingClientToRuntime(row);\n- const fieldsetTitle = name || formatMessage({ id: 'tasks.task-fieldsets' });\n+ const { name, title, fields, apiNameBinding } = mapFieldsetBindingClientToRuntime(row);\n return (\n \n
\n- \n- {formatMessage({ id: 'fieldsets.title' })}: {fieldsetTitle}\n+
\n+ {formatMessage({ id: 'fieldsets.header-label' })}: {name}\n
\n+ \n {isArrayWithItems(fields) &&\n
\n \n@@ -90,7 +95,7 @@ export function MergedOutputRows({\n
\n {/* sharedFieldsetId is synced with FieldsetIconPicker — do not replace with apiNameBinding */}\n onMoveRow(index, 'up')}", "status": "modified"}, {"additions": 80, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/__tests__/FieldsetEditorTitle.test.tsx", "patch": "@@ -0,0 +1,80 @@\n+import * as React from 'react';\n+import { render, screen } from '@testing-library/react';\n+import userEvent from '@testing-library/user-event';\n+\n+import { FieldsetEditorTitle } from '../FieldsetEditorTitle';\n+import { intlMock } from '../../../../__stubs__/intlMock';\n+\n+jest.mock('../../../icons', () => ({\n+ PencilSmallIcon: () => React.createElement('svg', { 'data-testid': 'pencil-icon' }),\n+}));\n+\n+jest.mock('../../../../utils/validators', () => ({\n+ validateFieldsetTitle: jest.fn((val: string) => (val ? '' : 'Title is required')),\n+}));\n+\n+describe('FieldsetEditorTitle', () => {\n+ const mockOnEditFieldsetTitle = jest.fn();\n+ const formatMsg = (id: string) => intlMock.formatMessage({ id });\n+\n+ const DEFAULT_PROPS = {\n+ apiNameBinding: 'fs-binding-1',\n+ title: 'Initial Fieldset Title',\n+ onEditFieldsetTitle: mockOnEditFieldsetTitle,\n+ formatMessage: intlMock.formatMessage,\n+ };\n+\n+ beforeEach(() => {\n+ jest.clearAllMocks();\n+ });\n+\n+ describe('Rendering', () => {\n+ it('renders title label, textarea with initial value, and pencil icon', () => {\n+ render(React.createElement(FieldsetEditorTitle, DEFAULT_PROPS));\n+\n+ expect(screen.getByText(`${formatMsg('fieldsets.title-label')}:`)).toBeInTheDocument();\n+\n+ const textarea = screen.getByRole('textbox');\n+ expect(textarea).toHaveValue('Initial Fieldset Title');\n+\n+ expect(screen.getByTestId('pencil-icon')).toBeInTheDocument();\n+ });\n+ });\n+\n+ describe('Editing and callbacks', () => {\n+ it('calls onEditFieldsetTitle on blur when value changes', () => {\n+ render(React.createElement(FieldsetEditorTitle, DEFAULT_PROPS));\n+\n+ const textarea = screen.getByRole('textbox');\n+\n+ userEvent.clear(textarea);\n+ userEvent.type(textarea, 'New Fieldset Title');\n+ textarea.blur();\n+\n+ expect(mockOnEditFieldsetTitle).toHaveBeenCalledTimes(1);\n+ expect(mockOnEditFieldsetTitle).toHaveBeenCalledWith('fs-binding-1', 'New Fieldset Title');\n+ });\n+\n+ it('does NOT call onEditFieldsetTitle if title value did not change on blur', () => {\n+ render(React.createElement(FieldsetEditorTitle, DEFAULT_PROPS));\n+\n+ const textarea = screen.getByRole('textbox');\n+\n+ userEvent.click(textarea);\n+ textarea.blur();\n+\n+ expect(mockOnEditFieldsetTitle).not.toHaveBeenCalled();\n+ });\n+\n+ it('blurs textarea when Enter key is pressed', () => {\n+ render(React.createElement(FieldsetEditorTitle, DEFAULT_PROPS));\n+\n+ const textarea = screen.getByRole('textbox');\n+ userEvent.click(textarea);\n+\n+ userEvent.type(textarea, '{enter}');\n+\n+ expect(screen.getByTestId('pencil-icon')).toBeInTheDocument();\n+ });\n+ });\n+});", "status": "added"}, {"additions": 17, "deletions": 19, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/__tests__/MergedOutputRows.test.tsx", "patch": "@@ -62,6 +62,11 @@ jest.mock('../FieldsetFlowRowDropdown', () => ({\n ),\n }));\n \n+jest.mock('../FieldsetEditorTitle', () => ({\n+ FieldsetEditorTitle: ({ title }: { title: string }) =>\n+ React.createElement('div', { 'data-testid': 'fieldset-editor-title' }, title),\n+}));\n+\n const makeField = (apiName: string) => makeExtraField({\n apiName,\n name: `Field ${apiName}`,\n@@ -72,10 +77,11 @@ const fieldRow = (apiName: string): TMergedTaskOutputRow => ({\n field: makeField(apiName),\n });\n \n-const fieldsetRow = (apiNameBinding: string, name = 'Test Fieldset', fieldsCount = 0): TMergedTaskOutputRow => ({\n+const fieldsetRow = (apiNameBinding: string, name = 'Test Fieldset', fieldsCount = 0, title?: string): TMergedTaskOutputRow => ({\n ...makeFieldsetBindingClient({\n apiNameBinding,\n name,\n+ title: title ?? `Title of ${name}`,\n fields: Array.from({ length: fieldsCount }, (_, index) =>\n makeFieldsetField({ apiName: `${apiNameBinding}-field-${index}` }),\n ),\n@@ -90,6 +96,7 @@ describe('MergedOutputRows', () => {\n onMoveRow: jest.fn(),\n onEditField: jest.fn(() => jest.fn()),\n onRemoveFieldset: jest.fn(),\n+ onEditFieldsetTitle: jest.fn(),\n datasetOptions: [],\n accountId: 1,\n formatMessage: intlMock.formatMessage,\n@@ -103,31 +110,22 @@ describe('MergedOutputRows', () => {\n expect(screen.getByText('Field f-1')).toBeInTheDocument();\n });\n \n- it('fieldset with name → renders \": \" with exact text', () => {\n- const prefix = intlMock.formatMessage({ id: 'fieldsets.title' });\n-\n- render(\n- React.createElement(\n- MergedOutputRows,\n- makeProps({ mergedRows: [fieldsetRow('fs-1', 'Fieldset Alpha')] }),\n- ),\n- );\n-\n- expect(screen.getByText(`${prefix}: Fieldset Alpha`)).toBeInTheDocument();\n- });\n-\n- it('fieldset with empty name → renders \": \" with exact text', () => {\n- const prefix = intlMock.formatMessage({ id: 'fieldsets.title' });\n- const fallback = intlMock.formatMessage({ id: 'tasks.task-fieldsets' });\n+ it('fieldset row → renders header with catalog name inline and FieldsetEditorTitle with title', () => {\n+ const HEADER_LABEL = intlMock.formatMessage({ id: 'fieldsets.header-label' });\n \n render(\n React.createElement(\n MergedOutputRows,\n- makeProps({ mergedRows: [fieldsetRow('fs-empty', '')] }),\n+ makeProps({\n+ mergedRows: [\n+ fieldsetRow('fs-1', 'Fieldset Alpha', 0, 'Custom Title Alpha'),\n+ ],\n+ }),\n ),\n );\n \n- expect(screen.getByText(`${prefix}: ${fallback}`)).toBeInTheDocument();\n+ expect(screen.getByText(`${HEADER_LABEL}: Fieldset Alpha`)).toBeInTheDocument();\n+ expect(screen.getByTestId('fieldset-editor-title')).toHaveTextContent('Custom Title Alpha');\n });\n \n it('renders ExtraFieldsLabels when fieldset has fields', () => {", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/types.ts", "patch": "@@ -0,0 +1,6 @@\n+export interface IFieldsetEditorTitleProps {\n+ apiNameBinding: string;\n+ title: string;\n+ onEditFieldsetTitle: (apiNameBinding: string, title: string) => void;\n+ formatMessage: (descriptor: { id: string }) => string;\n+}", "status": "added"}, {"additions": 31, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/utils/__tests__/areFieldsetsValid.test.ts", "patch": "@@ -0,0 +1,31 @@\n+import { areFieldsetsValid } from '../areFieldsetsValid';\n+import { makeFieldsetBindingClient } from '../../../../__stubs__/fieldsets.factory';\n+\n+describe('areFieldsetsValid', () => {\n+ it('returns true when all fieldsets have valid titles', () => {\n+ const fieldsets = [\n+ makeFieldsetBindingClient({ title: 'Customer Details' }),\n+ makeFieldsetBindingClient({ title: 'Payment Options' }),\n+ ];\n+ expect(areFieldsetsValid(fieldsets)).toBe(true);\n+ });\n+\n+ it('returns false when a fieldset has an empty title', () => {\n+ const fieldsets = [\n+ makeFieldsetBindingClient({ title: 'Customer Details' }),\n+ makeFieldsetBindingClient({ title: '' }),\n+ ];\n+ expect(areFieldsetsValid(fieldsets)).toBe(false);\n+ });\n+\n+ it('returns false when a fieldset title is only whitespace', () => {\n+ const fieldsets = [\n+ makeFieldsetBindingClient({ title: ' ' }),\n+ ];\n+ expect(areFieldsetsValid(fieldsets)).toBe(false);\n+ });\n+\n+ it('returns true for empty fieldsets list', () => {\n+ expect(areFieldsetsValid([])).toBe(true);\n+ });\n+});", "status": "added"}, {"additions": 3, "deletions": 3, "filename": "frontend/src/public/components/TemplateEdit/utils/__tests__/getRunnableWorkflow.test.ts", "patch": "@@ -1,4 +1,4 @@\n-import { ETaskPerformerType, EExtraFieldType, IKickoffClient } from '../../../../types/template';\n+import { ETaskPerformerType, EExtraFieldType, ITemplateKickoffClient } from '../../../../types/template';\n import { IFieldsetRuntime } from '../../../../types/fieldset';\n import { makeExtraField } from '../../../../__stubs__/fields.factory';\n import { makeFieldsetRuntime } from '../../../../__stubs__/fieldsets.factory';\n@@ -200,7 +200,7 @@ describe('getRunnableWorkflow.', () => {\n \n \n it('loadDatasetsMap returns {} and does not call getDataset when there are no dataset ids', async () => {\n- const kickoff: IKickoffClient = { description: '', fields: [], fieldsets: [] };\n+ const kickoff: ITemplateKickoffClient = { description: '', fields: [], fieldsets: [] };\n \n const result = await loadDatasetsMap(kickoff, []);\n \n@@ -209,7 +209,7 @@ describe('getRunnableWorkflow.', () => {\n });\n \n it('loadDatasetsMap dedups dataset id shared by a kickoff field and a fieldset field', async () => {\n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n description: '',\n fields: [makeExtraField({ apiName: 'k-f', name: 'K', type: EExtraFieldType.Checkbox, dataset: 7 })],\n fieldsets: [],", "status": "modified"}, {"additions": 6, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/utils/areFieldsetsValid.ts", "patch": "@@ -0,0 +1,6 @@\n+import { IFieldsetBindingClient } from '../../../types/fieldset';\n+import { validateFieldsetTitle } from '../../../utils/validators';\n+\n+export function areFieldsetsValid(fieldsets: IFieldsetBindingClient[] = []): boolean {\n+ return fieldsets.every((fieldset) => !validateFieldsetTitle(fieldset.title));\n+}", "status": "added"}, {"additions": 4, "deletions": 4, "filename": "frontend/src/public/components/TemplateEdit/utils/getRunnableWorkflow.ts", "patch": "@@ -1,6 +1,6 @@\n /* eslint-disable */\n /* prettier-ignore */\n-import { ITemplateClient, ITemplateTaskClient, IKickoffClient, IExtraField } from '../../../types/template';\n+import { ITemplateClient, ITemplateTaskClient, ITemplateKickoffClient, IExtraField } from '../../../types/template';\n import { IFieldsetRuntime } from '../../../types/fieldset';\n import { setPerformersCounts } from '../../../utils/template';\n import { IRunWorkflow } from '../../WorkflowEditPopup/types';\n@@ -15,7 +15,7 @@ export type TTemplateToRunWorkflow = Pick<\n \n import { getDataset } from '../../../api/datasets/getDataset';\n \n-function getKickoffDatasetIds(kickoff: IKickoffClient, fieldsets: IFieldsetRuntime[] = []): number[] {\n+function getKickoffDatasetIds(kickoff: ITemplateKickoffClient, fieldsets: IFieldsetRuntime[] = []): number[] {\n const ids = new Set();\n for (const field of kickoff.fields) {\n if (field.dataset) ids.add(field.dataset);\n@@ -28,7 +28,7 @@ function getKickoffDatasetIds(kickoff: IKickoffClient, fieldsets: IFieldsetRunti\n return [...ids];\n }\n \n-export async function loadDatasetsMap(kickoff: IKickoffClient, fieldsets: IFieldsetRuntime[] = []): Promise> {\n+export async function loadDatasetsMap(kickoff: ITemplateKickoffClient, fieldsets: IFieldsetRuntime[] = []): Promise> {\n const datasetIds = getKickoffDatasetIds(kickoff, fieldsets);\n if (datasetIds.length === 0) {\n return {};\n@@ -56,7 +56,7 @@ function applyDatasetsToFields(fields: IExtraField[], datasetsMap: Record): IKickoffClient {\n+function convertSelectionsToValues(kickoff: ITemplateKickoffClient, datasetsMap: Record): ITemplateKickoffClient {\n return {\n ...kickoff,\n fields: applyDatasetsToFields(kickoff.fields, datasetsMap),", "status": "modified"}, {"additions": 2, "deletions": 3, "filename": "frontend/src/public/components/TemplateEdit/utils/isValidTaskForm.ts", "patch": "@@ -1,8 +1,7 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n import { ITemplateTaskClient } from '../../../types/template';\n import { areExtraFieldsValid } from './areExtraFieldsValid';\n+import { areFieldsetsValid } from './areFieldsetsValid';\n \n export function isValidTaskForm(task: ITemplateTaskClient) {\n- return areExtraFieldsValid(task.fields);\n+ return areExtraFieldsValid(task.fields) && areFieldsetsValid(task.fieldsets);\n }", "status": "modified"}, {"additions": 2, "deletions": 1, "filename": "frontend/src/public/components/TemplateEdit/utils/validateTemplate.ts", "patch": "@@ -8,6 +8,7 @@ import { validateWorkflowName } from '../../../utils/validators';\n import { UnassignedTasksWarning, PremiumFeaturesWarning, IInfoWarningProps } from '../InfoWarningsModal/warnings';\n import { areConditionsValid, isNumberConditionsValid } from '../TaskForm/Conditions/utils/conditionsValidators';\n import { areExtraFieldsValid } from './areExtraFieldsValid';\n+import { areFieldsetsValid } from './areFieldsetsValid';\n import { isValidTaskForm } from './isValidTaskForm';\n \n type TWarningRule = {\n@@ -40,7 +41,7 @@ export function validateTemplate(template: ITemplateClient, isSubscribed: boolea\n getMessage: () => formatMessage({ id: 'template.task-validation-error' }),\n },\n {\n- check: () => !areExtraFieldsValid(kickoff!.fields),\n+ check: () => !areExtraFieldsValid(kickoff!.fields) || !areFieldsetsValid(kickoff!.fieldsets),\n getMessage: () => formatMessage({ id: 'template.kickoff-validation-error' }),\n },\n {", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "frontend/src/public/components/TuneViewModal/TuneViewModal.css", "patch": "@@ -111,6 +111,8 @@\n margin-bottom: 0.8rem;\n font-weight: bold;\n color: var(--pneumatic-color-black48);\n+\n+ @mixin text-wrap;\n }\n \n .tune-view-modal__tooltip {", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/public/components/TuneViewModal/TuneViewModal.tsx", "patch": "@@ -211,7 +211,7 @@ export function TuneViewModal() {\n if (output.kind === 'fieldset') {\n return (\n
\n-
{output.data.name}
\n+
{output.data.title}
\n {output.data.fields.map(renderFieldCheckbox)}\n
\n );", "status": "modified"}, {"additions": 41, "deletions": 12, "filename": "frontend/src/public/components/TuneViewModal/__tests__/TuneViewModal.test.tsx", "patch": "@@ -92,13 +92,21 @@ const makeField = (overrides: Partial = {}) => makeExtraField({\n ...overrides,\n });\n \n-const makeFieldsetOutput = (\n- apiNameBinding: string,\n- name: string,\n- fields: IExtraField[],\n-): TRuntimeMergedOutputPart => ({\n+type TMakeFieldsetOutputArgs = {\n+ apiNameBinding?: string;\n+ name?: string;\n+ title?: string;\n+ fields?: IExtraField[];\n+};\n+\n+const makeFieldsetOutput = ({\n+ apiNameBinding = 'fs-1',\n+ name = 'Catalog FS Name',\n+ title = 'FS Title',\n+ fields = [],\n+}: TMakeFieldsetOutputArgs = {}): TRuntimeMergedOutputPart => ({\n kind: 'fieldset' as const,\n- data: { apiNameBinding, name, description: '', fields, order: 0, labelPosition: EFieldLabelPosition.Top },\n+ data: { apiNameBinding, name, title, description: '', fields, order: 0, labelPosition: EFieldLabelPosition.Top },\n });\n \n const makeFieldOutput = (field: IExtraField): TRuntimeMergedOutputPart => ({\n@@ -135,15 +143,21 @@ describe('TuneViewModal', () => {\n \n const task = makeTask('task-1', 'Task 1', [\n makeFieldOutput(regularField),\n- makeFieldsetOutput('fs-1', 'My Fieldset', [fsField1, fsField2]),\n+ makeFieldsetOutput({\n+ apiNameBinding: 'fs-1',\n+ name: 'Catalog FS Name',\n+ title: 'My Fieldset Title',\n+ fields: [fsField1, fsField2],\n+ }),\n ]);\n \n mockTemplateTasks.mockReturnValue([task]);\n mockSavedFields.mockReturnValue(['reg-1']);\n \n renderWithIntl(React.createElement(TuneViewModal));\n \n- expect(screen.getByText('My Fieldset')).toBeInTheDocument();\n+ expect(screen.getByText('My Fieldset Title')).toBeInTheDocument();\n+ expect(screen.queryByText('Catalog FS Name')).not.toBeInTheDocument();\n expect(screen.getByTestId('cb-fs-f1')).toBeInTheDocument();\n expect(screen.getByTestId('cb-fs-f2')).toBeInTheDocument();\n expect(screen.getByTestId('cb-reg-1')).toBeInTheDocument();\n@@ -152,7 +166,12 @@ describe('TuneViewModal', () => {\n it('toggles fieldset field checked state', () => {\n const fsField = makeField({ apiName: 'fs-toggle', name: 'Toggle Me' });\n const task = makeTask('task-1', 'Task 1', [\n- makeFieldsetOutput('fs-1', 'FS', [fsField]),\n+ makeFieldsetOutput({\n+ apiNameBinding: 'fs-1',\n+ name: 'Catalog FS Name',\n+ title: 'FS Title',\n+ fields: [fsField],\n+ }),\n ]);\n \n mockTemplateTasks.mockReturnValue([task]);\n@@ -171,15 +190,20 @@ describe('TuneViewModal', () => {\n it('auto-expands task when a fieldset field is in savedFields', () => {\n const fsField = makeField({ apiName: 'fs-saved', name: 'Saved FS Field' });\n const task = makeTask('task-auto', 'Auto Task', [\n- makeFieldsetOutput('fs-auto', 'Auto FS', [fsField]),\n+ makeFieldsetOutput({\n+ apiNameBinding: 'fs-auto',\n+ name: 'Auto FS Catalog Name',\n+ title: 'Auto FS Title',\n+ fields: [fsField],\n+ }),\n ]);\n \n mockTemplateTasks.mockReturnValue([task]);\n mockSavedFields.mockReturnValue(['fs-saved']);\n \n renderWithIntl(React.createElement(TuneViewModal));\n \n- expect(screen.getByText('Auto FS')).toBeInTheDocument();\n+ expect(screen.getByText('Auto FS Title')).toBeInTheDocument();\n expect(screen.getByTestId('cb-fs-saved')).toBeInTheDocument();\n });\n \n@@ -192,7 +216,12 @@ describe('TuneViewModal', () => {\n \n const task = makeTask('task-1', 'Task 1', [\n makeFieldOutput(regularField),\n- makeFieldsetOutput('fs-1', 'FS', [fsField1, fsField2]),\n+ makeFieldsetOutput({\n+ apiNameBinding: 'fs-1',\n+ name: 'Catalog FS Name',\n+ title: 'FS Title',\n+ fields: [fsField1, fsField2],\n+ }),\n ]);\n \n mockTemplateTasks.mockReturnValue([task]);", "status": "modified"}, {"additions": 3, "deletions": 2, "filename": "frontend/src/public/components/WorkflowEditPopup/types.ts", "patch": "@@ -1,10 +1,11 @@\n-import { ITemplateClient } from '../../types/template';\n+import { ITemplateClient, ITemplateKickoffClient, IRuntimeKickoffClient } from '../../types/template';\n import { IFieldsetRuntime } from '../../types/fieldset';\n \n-export interface IRunWorkflow extends Pick {\n+export interface IRunWorkflow extends Omit, 'kickoff'> {\n id: number;\n tasksCount: number;\n performersCount: number;\n+ kickoff: ITemplateKickoffClient | IRuntimeKickoffClient;\n isUrgent?: boolean;\n ancestorTaskId?: number;\n dueDate?: string;", "status": "modified"}, {"additions": 2, "deletions": 4, "filename": "frontend/src/public/components/WorkflowEditPopup/utils/getInitialKickoff.ts", "patch": "@@ -1,8 +1,6 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n-import { IKickoffClient } from '../../../types/template';\n+import { ITemplateKickoffClient, IRuntimeKickoffClient } from '../../../types/template';\n import { ExtraFieldsHelper } from '../../TemplateEdit/ExtraFields/utils/ExtraFieldsHelper';\n \n-export function getInitialKickoff(kickoff: IKickoffClient): IKickoffClient {\n+export function getInitialKickoff(kickoff: T): T {\n return { ...kickoff, fields: new ExtraFieldsHelper(kickoff.fields).getFieldsWithValues() };\n }", "status": "modified"}, {"additions": 22, "deletions": 18, "filename": "frontend/src/public/components/Workflows/WorkflowsGridPage/WorkflowCard/utils/__tests__/getClonedKickoff.test.ts", "patch": "@@ -1,7 +1,7 @@\n import { IWorkflowDetailsKickoff } from '../../../../../../types/workflow';\n-import { EExtraFieldType, IKickoffClient, IFieldsetBindingClient } from '../../../../../../types/template';\n+import { EExtraFieldType, ITemplateKickoffClient } from '../../../../../../types/template';\n import { IFieldsetRuntime } from '../../../../../../types/fieldset';\n-import { makeFieldsetRuntime } from '../../../../../../__stubs__/fieldsets.factory';\n+import { makeFieldsetRuntime, makeFieldsetBindingClient, makeFieldsetField } from '../../../../../../__stubs__/fieldsets.factory';\n import { makeExtraField } from '../../../../../../__stubs__/fields.factory';\n import { getClonedKickoff } from '../getClonedKickoff';\n \n@@ -119,7 +119,7 @@ const mockWorkflowDetailKickoff: IWorkflowDetailsKickoff = {\n ],\n };\n \n-const templateKickoffMock: IKickoffClient = {\n+const templateKickoffMock: ITemplateKickoffClient = {\n description:\n ' youtube: \\nhttps://www.youtube.com/watch?v=JZRm7NKTPhk\\n loom:\\nhttps://www.loom.com/share/29f210bc12484eaa81ca462381fb4415?t=0\\n 404 loom:\\n\\nhttps://www.loom.com/share/9853f0790ad2408094a3717bfcf4a0c0\\nYoutube 404 :\\n\\nhttps://www.youtube.com/watch?v=D6hIeqZt22g',\n fields: [\n@@ -333,7 +333,7 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const emptyTemplateKickoff: IKickoffClient = {\n+ const emptyTemplateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [],\n fieldsets: [],\n@@ -371,7 +371,7 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const templateKickoff: IKickoffClient = {\n+ const templateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [\n {\n@@ -411,7 +411,7 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const templateKickoff: IKickoffClient = {\n+ const templateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [\n {\n@@ -455,22 +455,26 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const templateKickoff: IKickoffClient = {\n+ const templateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [],\n fieldsets: [\n- makeFieldsetRuntime({\n+ makeFieldsetBindingClient({\n apiNameBinding: 'fs-1',\n name: 'Fieldset 1',\n fields: [\n- makeExtraField({\n+ makeFieldsetField({\n apiName: 'fs-field-1',\n name: 'FS Checkbox',\n type: EExtraFieldType.Checkbox,\n- selections: ['Opt1', 'Opt2', 'Opt3'],\n+ selections: [\n+ { apiName: 'Opt1', value: 'Opt1' },\n+ { apiName: 'Opt2', value: 'Opt2' },\n+ { apiName: 'Opt3', value: 'Opt3' },\n+ ],\n }),\n ],\n- }) as unknown as IFieldsetBindingClient,\n+ }),\n ],\n };\n \n@@ -495,15 +499,15 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const templateKickoff: IKickoffClient = {\n+ const templateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [],\n fieldsets: [\n- makeFieldsetRuntime({\n+ makeFieldsetBindingClient({\n apiNameBinding: 'fs-valid',\n name: 'Valid Fieldset',\n fields: [],\n- }) as unknown as IFieldsetBindingClient,\n+ }),\n ],\n };\n \n@@ -534,21 +538,21 @@ describe('getClonedKickoff', () => {\n ],\n };\n \n- const templateKickoff: IKickoffClient = {\n+ const templateKickoff: ITemplateKickoffClient = {\n description: '',\n fields: [],\n fieldsets: [\n- makeFieldsetRuntime({\n+ makeFieldsetBindingClient({\n apiNameBinding: 'raw-backend-fs',\n name: 'Template Fieldset',\n fields: [\n- makeExtraField({\n+ makeFieldsetField({\n apiName: 'raw-field-1',\n name: 'Field 1',\n type: EExtraFieldType.String,\n }),\n ],\n- }) as unknown as IFieldsetBindingClient,\n+ }),\n ],\n };\n ", "status": "modified"}, {"additions": 8, "deletions": 11, "filename": "frontend/src/public/components/Workflows/WorkflowsGridPage/WorkflowCard/utils/getClonedKickoff.ts", "patch": "@@ -3,15 +3,15 @@\n import {\n EExtraFieldType,\n IExtraField,\n- IKickoffClient,\n+ ITemplateKickoffClient,\n+ IRuntimeKickoffClient,\n TExtraFieldValue,\n- IFieldsetBindingClient,\n } from '../../../../../types/template';\n import { IWorkflowDetailsKickoff } from '../../../../../types/workflow';\n import { getEditKickoff } from '../../../../../utils/workflows';\n import { normalizeSelections } from '../../../../TemplateEdit/utils/normalizeSelections';\n import { normalizeCheckboxValue } from '../../../../../utils/fields';\n-import { IFieldsetField } from '../../../../../types/fieldset';\n+import { IFieldsetField, IFieldsetRuntime } from '../../../../../types/fieldset';\n \n function normalizeKickoffFields(\n fields: (IExtraField | IFieldsetField)[] = [],\n@@ -31,12 +31,12 @@ function normalizeKickoffFields(\n \n export function getClonedKickoff(\n workflowKickoff: IWorkflowDetailsKickoff,\n- templateKickoff: IKickoffClient,\n-): IKickoffClient {\n+ templateKickoff: ITemplateKickoffClient,\n+): IRuntimeKickoffClient {\n const kickoff = getEditKickoff(workflowKickoff);\n const finalFields = normalizeKickoffFields(kickoff.fields, templateKickoff.fields);\n \n- const finalFieldsets = (kickoff.fieldsets || [])\n+ const finalFieldsets: IFieldsetRuntime[] = (kickoff.fieldsets || [])\n .map((fieldset) => {\n // TODO (Technical Debt): Backend workflow fieldsets contain raw properties (id, apiName),\n // while client-side template fieldsets expect apiNameBinding.\n@@ -56,15 +56,12 @@ export function getClonedKickoff(\n fields: normalizeKickoffFields(fieldset.fields, templateFieldset.fields),\n };\n })\n- .filter(Boolean);\n+ .filter((fieldset): fieldset is IFieldsetRuntime => Boolean(fieldset));\n \n- // TODO (Technical Debt): IKickoffClient.fieldsets is typed as IFieldsetBindingClient[] (template editor shape),\n- // but runtime workflow execution components expect IFieldsetRuntime[] (with IExtraField[]).\n- // Cast is required until IKickoffClient type is separated/narrowed between editor and runtime contexts.\n return {\n ...kickoff,\n fields: finalFields,\n- fieldsets: finalFieldsets as unknown as IFieldsetBindingClient[],\n+ fieldsets: finalFieldsets,\n };\n }\n ", "status": "modified"}, {"additions": 33, "deletions": 2, "filename": "frontend/src/public/lang/locales/en_US.ts", "patch": "@@ -1370,12 +1370,33 @@ export const enMessages = {\n 'integrations.list-fetch-failed': 'Failed to fetch integrations',\n 'integrations.details-fetch-failed': \"Failed to fetch integration's details\",\n 'integrations.not-found': 'Integration is not found',\n- 'integrations.loading-api-key': 'Loading your API-key…',\n+ 'integrations.loading-api-key': 'Loading your API keys…',\n 'integrations.connect-account': 'Connect You Account',\n 'integrations.support-email': 'support@pneumatic.app',\n 'integrations.copy-api-key': 'Copy Key',\n 'integrations.api-key-title': 'Your API Key',\n- 'integrations.fetch-api-key-error': 'Failed to fetch API key',\n+ 'integrations.fetch-api-key-error': 'Failed to fetch API keys',\n+ 'integrations.api-keys-title': 'Your API Keys',\n+ 'integrations.create-api-key': 'Create',\n+ 'integrations.create-api-key-modal-title': 'New API Key',\n+ 'integrations.create-api-key-modal-description': 'Give your API key a descriptive name so you can identify it later.',\n+ 'integrations.api-key-created-title': 'Key Created Successfully',\n+ 'integrations.api-key-created-warning': 'Copy this key now. You won\\'t be able to see it again.',\n+ 'integrations.api-key-copied': '✓ Copied!',\n+ 'integrations.api-key-copy': 'Copy Key',\n+ 'integrations.delete-api-key-confirm': 'Are you sure? Integrations using this key will stop working.',\n+ 'integrations.api-key-name-label': 'Key Name',\n+ 'integrations.api-key-name-placeholder': 'e.g. CI/CD Pipeline',\n+ 'integrations.api-key-last-used': 'Last used: {date}',\n+ 'integrations.api-key-never-used': 'Never used',\n+ 'integrations.api-key-revoke': 'Revoke',\n+ 'integrations.revoke-modal-title': 'Revoke API Key',\n+ 'integrations.api-key-revoked': 'Key revoked successfully',\n+ 'integrations.api-key-done': 'Done',\n+ 'integrations.no-api-keys': 'No API keys yet. Create your first key to get started.',\n+ 'integrations.cancel': 'Cancel',\n+ 'integrations.create-api-key-error': 'Failed to create API key',\n+ 'integrations.delete-api-key-error': 'Failed to revoke API key',\n \n 'tenants.delete-title': 'Delete Tenant',\n 'tenants.delete-message': 'Do you really want to delete {name} — it will not longer be able to use the system. ',\n@@ -1503,6 +1524,7 @@ export const enMessages = {\n 'fieldsets.no-fields': 'No fields yet',\n 'fieldsets.no-rules': 'No rules yet',\n 'fieldsets.save': 'Save',\n+ 'fieldsets.save-success': 'Fieldset saved successfully',\n 'fieldsets.unsaved-changes': 'You have unsaved changes',\n 'fieldsets.add-field': 'Add field',\n 'fieldsets.add-rule': 'Add Rule',\n@@ -1525,8 +1547,15 @@ export const enMessages = {\n 'fieldsets.leave-unsaved-save': 'Save',\n 'fieldsets.clone-unsaved-warning': 'Please save or discard unsaved changes before cloning',\n 'fieldsets.settings-section': 'Settings',\n+ 'fieldsets.header-label': 'Fieldset',\n+ 'fieldsets.name-label': 'Name',\n+ 'fieldsets.title-label': 'Title',\n+ 'fieldsets.settings.title': 'Title',\n+ 'fieldsets.settings.title-placeholder': 'Enter fieldset title...',\n+ 'fieldsets.settings.title-tooltip': 'Title for the user',\n 'fieldsets.settings.description': 'Description',\n 'fieldsets.settings.description-placeholder': 'Enter fieldset description...',\n+ 'fieldsets.settings.description-tooltip': 'Description of the form for the user',\n 'fieldsets.settings.label-position': 'Label Position',\n 'fieldsets.settings.label-position.top': 'Top',\n 'fieldsets.settings.label-position.left': 'Left',\n@@ -1540,6 +1569,8 @@ export const enMessages = {\n 'fieldsets.settings.layout.vertical': 'Vertical',\n 'validation.fieldset-name-empty': 'Please enter a fieldset name',\n 'validation.fieldset-name-to-long': 'The fieldset name is longer than 200 characters',\n+ 'validation.fieldset-title-empty': 'Fieldset title is required',\n+ 'validation.fieldset-title-to-long': 'The fieldset title is longer than 200 characters',\n 'template.kick-off-fieldsets': 'Fieldsets',\n 'tasks.task-fieldsets': 'Fieldsets',\n 'template.fieldset-picker.placeholder': 'Select fieldsets...',", "status": "modified"}, {"additions": 33, "deletions": 2, "filename": "frontend/src/public/lang/locales/ru_RU.ts", "patch": "@@ -1264,12 +1264,33 @@ export const ruMessages = {\n 'integrations.list-fetch-failed': 'Не удалось получить интеграции',\n 'integrations.details-fetch-failed': 'Не удалось получить детали интеграции',\n 'integrations.not-found': 'Интеграция не найдена',\n- 'integrations.loading-api-key': 'Загрузка вашего API-ключа…',\n+ 'integrations.loading-api-key': 'Загрузка ваших API-ключей…',\n 'integrations.connect-account': 'Подключите Ваш Аккаунт',\n 'integrations.support-email': 'support@pneumatic.app',\n 'integrations.copy-api-key': 'Копировать ключ',\n 'integrations.api-key-title': 'Ваш API ключ',\n- 'integrations.fetch-api-key-error': 'Не удалось получить ключ API',\n+ 'integrations.fetch-api-key-error': 'Не удалось получить ключи API',\n+ 'integrations.api-keys-title': 'Ваши API-ключи',\n+ 'integrations.create-api-key': 'Создать',\n+ 'integrations.create-api-key-modal-title': 'Новый API-ключ',\n+ 'integrations.create-api-key-modal-description': 'Задайте ключу понятное имя, чтобы легко находить его в будущем.',\n+ 'integrations.api-key-created-title': 'Ключ успешно создан',\n+ 'integrations.api-key-created-warning': 'Скопируйте этот ключ сейчас. Вы не сможете увидеть его снова.',\n+ 'integrations.api-key-copied': '✓ Скопировано!',\n+ 'integrations.api-key-copy': 'Копировать ключ',\n+ 'integrations.delete-api-key-confirm': 'Вы уверены? Интеграции, использующие этот ключ, перестанут работать.',\n+ 'integrations.api-key-name-label': 'Имя ключа',\n+ 'integrations.api-key-name-placeholder': 'напр. CI/CD Pipeline',\n+ 'integrations.api-key-last-used': 'Последнее использование: {date}',\n+ 'integrations.api-key-never-used': 'Не использовался',\n+ 'integrations.api-key-revoke': 'Отозвать',\n+ 'integrations.revoke-modal-title': 'Отозвать API-ключ',\n+ 'integrations.api-key-revoked': 'Ключ успешно отозван',\n+ 'integrations.api-key-done': 'Готово',\n+ 'integrations.no-api-keys': 'API-ключей пока нет. Создайте первый ключ для начала работы.',\n+ 'integrations.cancel': 'Отмена',\n+ 'integrations.create-api-key-error': 'Не удалось создать API-ключ',\n+ 'integrations.delete-api-key-error': 'Не удалось отозвать API-ключ',\n 'tenants.delete-title': 'Удалить подразделение',\n 'tenants.delete-message': 'Вы действительно хотите удалить {name} — он больше не сможет использовать систему.',\n 'tenants.delete-accept': 'Отправить',\n@@ -1390,6 +1411,7 @@ export const ruMessages = {\n 'fieldsets.no-fields': 'Пока нет полей',\n 'fieldsets.no-rules': 'Пока нет правил',\n 'fieldsets.save': 'Сохранить',\n+ 'fieldsets.save-success': 'Набор полей успешно сохранён',\n 'fieldsets.unsaved-changes': 'Есть несохранённые изменения',\n 'fieldsets.add-field': 'Добавить поле',\n 'fieldsets.add-rule': 'Добавить правило',\n@@ -1415,8 +1437,15 @@ export const ruMessages = {\n 'fieldsets.clone-unsaved-warning':\n 'Пожалуйста, сохраните или отмените несохраненные изменения перед клонированием',\n 'fieldsets.settings-section': 'Настройки',\n+ 'fieldsets.header-label': 'Филдсет',\n+ 'fieldsets.name-label': 'Имя',\n+ 'fieldsets.title-label': 'Заголовок',\n+ 'fieldsets.settings.title': 'Заголовок',\n+ 'fieldsets.settings.title-placeholder': 'Введите заголовок набора полей...',\n+ 'fieldsets.settings.title-tooltip': 'Заголовок для пользователя',\n 'fieldsets.settings.description': 'Описание',\n 'fieldsets.settings.description-placeholder': 'Введите описание набора полей...',\n+ 'fieldsets.settings.description-tooltip': 'Описание формы для пользователя',\n 'fieldsets.settings.label-position': 'Позиция метки',\n 'fieldsets.settings.label-position.top': 'Сверху',\n 'fieldsets.settings.label-position.left': 'Слева',\n@@ -1430,6 +1459,8 @@ export const ruMessages = {\n 'fieldsets.settings.layout.vertical': 'Вертикальное',\n 'validation.fieldset-name-empty': 'Введите название набора полей',\n 'validation.fieldset-name-to-long': 'Название набора полей не должно превышать 200 символов',\n+ 'validation.fieldset-title-empty': 'Заголовок набора полей не может быть пустым',\n+ 'validation.fieldset-title-to-long': 'Заголовок набора полей не должен превышать 200 символов',\n 'template.kick-off-fieldsets': 'Наборы полей',\n 'tasks.task-fieldsets': 'Наборы полей',\n 'template.fieldset-picker.placeholder': 'Выберите наборы полей...',", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/redux/dashboard/saga.ts", "patch": "@@ -43,7 +43,7 @@ import { getTemplate } from '../../api/getTemplate';\n \n import { openRunWorkflowModal } from '../runWorkflowModal/actions';\n import { getRunnableWorkflow, loadDatasetsMap } from '../../components/TemplateEdit/utils/getRunnableWorkflow';\n-import { ITemplateResponse, IExtraField, IKickoffClient } from '../../types/template';\n+import { ITemplateResponse, IExtraField, ITemplateKickoffClient} from '../../types/template';\n import { IFieldsetRuntime } from '../../types/fieldset';\n import { mapTemplateFieldsetsToRuntime } from '../../utils/mapTemplateFieldsetsToRuntime';\n import { mapFieldsetBindingsToClient } from '../../utils/mapFieldsetsAPIToClient';\n@@ -175,7 +175,7 @@ export function* openRunWorflowByTemplateDataSaga({\n \n const kickoffFields = mapFieldsToExtraFields(templateData.kickoff?.fields || []);\n \n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n description: '',\n fields: kickoffFields,\n fieldsets: [],", "status": "modified"}, {"additions": 6, "deletions": 2, "filename": "frontend/src/public/redux/fieldsets/__tests__/saga.test.ts", "patch": "@@ -45,7 +45,7 @@ jest.mock('../../../utils/history', () => ({\n }));\n \n jest.mock('../../../components/UI/Notifications', () => ({\n- NotificationManager: { notifyApiError: jest.fn(), warning: jest.fn() },\n+ NotificationManager: { notifyApiError: jest.fn(), warning: jest.fn(), success: jest.fn() },\n }));\n \n jest.mock('../../../utils/logger', () => ({\n@@ -356,13 +356,17 @@ describe('updateFieldsetSaga', () => {\n return dispatched;\n };\n \n- it('dispatches setCurrentFieldset on API success', async () => {\n+ it('dispatches setCurrentFieldset and displays success notification on API success', async () => {\n const updatedFieldset = makeFieldsetCatalogItem({ id: FIELDSET_ID, name: 'Updated' });\n (updateFieldset as jest.Mock).mockResolvedValue(updatedFieldset);\n \n const dispatched = await runUpdateFieldset({ id: FIELDSET_ID, name: 'Updated' });\n \n expect(updateFieldset).toHaveBeenCalledTimes(1);\n+\n+ expect(NotificationManager.success).toHaveBeenCalledTimes(1);\n+ expect(NotificationManager.success).toHaveBeenCalledWith({ message: 'fieldsets.save-success' });\n+\n expect(dispatched).toEqual(\n expect.arrayContaining([\n expect.objectContaining({ type: setCurrentFieldset.type }),", "status": "modified"}, {"additions": 1, "deletions": 0, "filename": "frontend/src/public/redux/fieldsets/saga.ts", "patch": "@@ -121,6 +121,7 @@ export function* updateFieldsetSaga({ payload }: PayloadAction;\n-export const loadApiKey: (payload?: void) => TLoadApiKey =\n- actionGenerator(EIntegrationsActions.LoadApiKey);\n+// API Keys: Load\n+export type TLoadApiKeys = ITypedReduxAction;\n+export const loadApiKeys: (payload?: void) => TLoadApiKeys =\n+ actionGenerator(EIntegrationsActions.LoadApiKeys);\n \n-export type TLoadApiKeySuccess = ITypedReduxAction;\n-export const loadApiKeySuccess: (payload: string) => TLoadApiKeySuccess =\n- actionGenerator(EIntegrationsActions.LoadApiKeySuccess);\n+export type TLoadApiKeysSuccess = ITypedReduxAction;\n+export const loadApiKeysSuccess: (payload: IApiKeyItem[]) => TLoadApiKeysSuccess =\n+ actionGenerator(EIntegrationsActions.LoadApiKeysSuccess);\n \n-export type TLoadApiKeyFailed = ITypedReduxAction;\n-export const loadApiKeyFailed: (payload?: void) => TLoadApiKeyFailed =\n- actionGenerator(EIntegrationsActions.LoadApiKeyFailed);\n+export type TLoadApiKeysFailed = ITypedReduxAction;\n+export const loadApiKeysFailed: (payload?: void) => TLoadApiKeysFailed =\n+ actionGenerator(EIntegrationsActions.LoadApiKeysFailed);\n \n+// API Keys: Create\n+export type TCreateApiKeyPayload = { name?: string };\n+export type TCreateApiKey = ITypedReduxAction;\n+export const createApiKey: (payload: TCreateApiKeyPayload) => TCreateApiKey =\n+ actionGenerator(EIntegrationsActions.CreateApiKey);\n+\n+export type TCreateApiKeySuccessPayload = { apiKey: IApiKeyItem; rawKey: string };\n+export type TCreateApiKeySuccess = ITypedReduxAction;\n+export const createApiKeySuccess: (payload: TCreateApiKeySuccessPayload) => TCreateApiKeySuccess =\n+ actionGenerator(EIntegrationsActions.CreateApiKeySuccess);\n+\n+export type TCreateApiKeyFailed = ITypedReduxAction;\n+export const createApiKeyFailed: (payload?: void) => TCreateApiKeyFailed =\n+ actionGenerator(EIntegrationsActions.CreateApiKeyFailed);\n+\n+// API Keys: Delete\n+export type TDeleteApiKeyPayload = { id: number };\n+export type TDeleteApiKey = ITypedReduxAction;\n+export const deleteApiKey: (payload: TDeleteApiKeyPayload) => TDeleteApiKey =\n+ actionGenerator(EIntegrationsActions.DeleteApiKey);\n+\n+export type TDeleteApiKeySuccess = ITypedReduxAction;\n+export const deleteApiKeySuccess: (payload: { id: number }) => TDeleteApiKeySuccess =\n+ actionGenerator(EIntegrationsActions.DeleteApiKeySuccess);\n+\n+export type TDeleteApiKeyFailed = ITypedReduxAction;\n+export const deleteApiKeyFailed: (payload?: void) => TDeleteApiKeyFailed =\n+ actionGenerator(EIntegrationsActions.DeleteApiKeyFailed);\n+\n+// API Keys: Clear newly created\n+export type TClearNewlyCreatedKey = ITypedReduxAction;\n+export const clearNewlyCreatedKey: (payload?: void) => TClearNewlyCreatedKey =\n+ actionGenerator(EIntegrationsActions.ClearNewlyCreatedKey);\n+\n+// Integrations List\n export type TLoadIntegrationsList = ITypedReduxAction;\n export const loadIntegrationsList: (payload?: void) => TLoadIntegrationsList =\n actionGenerator(EIntegrationsActions.LoadIntegrationsList);\n@@ -45,6 +86,7 @@ export const loadIntegrationsListFailed: (payload?: void) => TLoadIntegrationsLi\n actionGenerator\n (EIntegrationsActions.LoadIntegrationsListFailed);\n \n+// Integration Details\n export type TLoadIntegrationDetailsPayload = { id: number };\n export type TLoadIntegrationDetails = ITypedReduxAction<\n EIntegrationsActions.LoadIntegrationDetails,\n@@ -69,9 +111,16 @@ export const loadIntegrationDetailsFailed: (payload?: void) => TLoadIntegrationD\n actionGenerator\n (EIntegrationsActions.LoadIntegrationDetailsFailed);\n \n-export type TIntegrationsActions = TLoadApiKey\n-| TLoadApiKeySuccess\n-| TLoadApiKeyFailed\n+export type TIntegrationsActions = TLoadApiKeys\n+| TLoadApiKeysSuccess\n+| TLoadApiKeysFailed\n+| TCreateApiKey\n+| TCreateApiKeySuccess\n+| TCreateApiKeyFailed\n+| TDeleteApiKey\n+| TDeleteApiKeySuccess\n+| TDeleteApiKeyFailed\n+| TClearNewlyCreatedKey\n | TLoadIntegrationsList\n | TLoadIntegrationsListSuccess\n | TLoadIntegrationsListFailed", "status": "modified"}, {"additions": 85, "deletions": 0, "filename": "frontend/src/public/redux/integrations/reducer.test.ts", "patch": "@@ -0,0 +1,85 @@\n+import { reducer } from './reducer';\n+import { EIntegrationsActions } from './actions';\n+import { IIntegrationsStore } from '../../types/redux';\n+import { IApiKeyItem } from '../../types/integrations';\n+\n+const mockApiKey: IApiKeyItem = {\n+ id: 1,\n+ name: 'Test Key',\n+ prefix: 'pn_live_',\n+ dateCreated: '2026-07-30T00:00:00Z',\n+ lastUsedAt: null,\n+ expiresAt: null,\n+ isActive: true,\n+};\n+\n+describe('integrations reducer', () => {\n+ let initialState: IIntegrationsStore;\n+\n+ beforeEach(() => {\n+ initialState = {\n+ apiKeys: { isLoading: false, data: [], newlyCreatedKey: null },\n+ list: { isLoading: false, data: [] },\n+ detailed: { isLoading: false, data: null },\n+ };\n+ });\n+\n+ it('should handle LoadApiKeys', () => {\n+ const action = { type: EIntegrationsActions.LoadApiKeys } as any;\n+ const nextState = reducer(initialState, action);\n+ expect(nextState.apiKeys.isLoading).toBe(true);\n+ });\n+\n+ it('should handle LoadApiKeysSuccess', () => {\n+ const action = {\n+ type: EIntegrationsActions.LoadApiKeysSuccess,\n+ payload: [mockApiKey],\n+ } as any;\n+ const nextState = reducer(initialState, action);\n+ expect(nextState.apiKeys.isLoading).toBe(false);\n+ expect(nextState.apiKeys.data).toEqual([mockApiKey]);\n+ });\n+\n+ it('should handle LoadApiKeysFailed', () => {\n+ const action = { type: EIntegrationsActions.LoadApiKeysFailed } as any;\n+ const state = {\n+ ...initialState,\n+ apiKeys: { ...initialState.apiKeys, isLoading: true },\n+ };\n+ const nextState = reducer(state, action);\n+ expect(nextState.apiKeys.isLoading).toBe(false);\n+ });\n+\n+ it('should handle CreateApiKeySuccess', () => {\n+ const action = {\n+ type: EIntegrationsActions.CreateApiKeySuccess,\n+ payload: { apiKey: mockApiKey, rawKey: 'pn_live_123' },\n+ } as any;\n+ const nextState = reducer(initialState, action);\n+ expect(nextState.apiKeys.data[0]).toEqual(mockApiKey);\n+ expect(nextState.apiKeys.newlyCreatedKey).toBe('pn_live_123');\n+ });\n+\n+ it('should handle DeleteApiKeySuccess', () => {\n+ const state = {\n+ ...initialState,\n+ apiKeys: { ...initialState.apiKeys, data: [mockApiKey] },\n+ };\n+ const action = {\n+ type: EIntegrationsActions.DeleteApiKeySuccess,\n+ payload: { id: 1 },\n+ } as any;\n+ const nextState = reducer(state, action);\n+ expect(nextState.apiKeys.data).toHaveLength(0);\n+ });\n+\n+ it('should handle ClearNewlyCreatedKey', () => {\n+ const state = {\n+ ...initialState,\n+ apiKeys: { ...initialState.apiKeys, newlyCreatedKey: 'pn_live_123' },\n+ };\n+ const action = { type: EIntegrationsActions.ClearNewlyCreatedKey } as any;\n+ const nextState = reducer(state, action);\n+ expect(nextState.apiKeys.newlyCreatedKey).toBeNull();\n+ });\n+});", "status": "added"}, {"additions": 58, "deletions": 44, "filename": "frontend/src/public/redux/integrations/reducer.ts", "patch": "@@ -1,14 +1,13 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n import produce from 'immer';\n \n import { EIntegrationsActions, TIntegrationsActions } from './actions';\n import { IIntegrationsStore } from '../../types/redux';\n \n const INIT_STATE: IIntegrationsStore = {\n- apiKey: {\n+ apiKeys: {\n isLoading: false,\n- data: '',\n+ data: [],\n+ newlyCreatedKey: null,\n },\n list: {\n isLoading: false,\n@@ -22,46 +21,61 @@ const INIT_STATE: IIntegrationsStore = {\n \n export const reducer = (state = INIT_STATE, action: TIntegrationsActions): IIntegrationsStore => {\n switch (action.type) {\n- case EIntegrationsActions.LoadApiKey:\n- return produce(state, draftState => {\n- draftState.apiKey.isLoading = true;\n- });\n- case EIntegrationsActions.LoadApiKeySuccess:\n- return produce(state, draftState => {\n- draftState.apiKey.data = action.payload;\n- draftState.apiKey.isLoading = false;\n- });\n- case EIntegrationsActions.LoadApiKeyFailed:\n- return produce(state, draftState => {\n- draftState.apiKey.isLoading = false;\n- });\n- case EIntegrationsActions.LoadIntegrationsList:\n- return produce(state, draftState => {\n- draftState.list.isLoading = true;\n- });\n- case EIntegrationsActions.LoadIntegrationsListSuccess:\n- return produce(state, draftState => {\n- draftState.list.data = action.payload;\n- draftState.list.isLoading = false;\n- });\n- case EIntegrationsActions.LoadIntegrationsListFailed:\n- return produce(state, draftState => {\n- draftState.list.isLoading = false;\n- });\n- case EIntegrationsActions.LoadIntegrationDetails:\n- return produce(state, draftState => {\n- draftState.detailed.isLoading = true;\n- });\n- case EIntegrationsActions.LoadIntegrationDetailsSuccess:\n- return produce(state, draftState => {\n- draftState.detailed.data = action.payload;\n- draftState.detailed.isLoading = false;\n- });\n- case EIntegrationsActions.LoadIntegrationDetailsFailed:\n- return produce(state, draftState => {\n- draftState.detailed.isLoading = false;\n- });\n+ case EIntegrationsActions.LoadApiKeys:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.isLoading = true;\n+ });\n+ case EIntegrationsActions.LoadApiKeysSuccess:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.data = action.payload;\n+ draftState.apiKeys.isLoading = false;\n+ });\n+ case EIntegrationsActions.LoadApiKeysFailed:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.isLoading = false;\n+ });\n+ case EIntegrationsActions.CreateApiKeySuccess:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.data.unshift(action.payload.apiKey);\n+ draftState.apiKeys.newlyCreatedKey = action.payload.rawKey;\n+ });\n+ case EIntegrationsActions.DeleteApiKeySuccess:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.data = draftState.apiKeys.data.filter(\n+ key => key.id !== action.payload.id,\n+ );\n+ });\n+ case EIntegrationsActions.ClearNewlyCreatedKey:\n+ return produce(state, draftState => {\n+ draftState.apiKeys.newlyCreatedKey = null;\n+ });\n+ case EIntegrationsActions.LoadIntegrationsList:\n+ return produce(state, draftState => {\n+ draftState.list.isLoading = true;\n+ });\n+ case EIntegrationsActions.LoadIntegrationsListSuccess:\n+ return produce(state, draftState => {\n+ draftState.list.data = action.payload;\n+ draftState.list.isLoading = false;\n+ });\n+ case EIntegrationsActions.LoadIntegrationsListFailed:\n+ return produce(state, draftState => {\n+ draftState.list.isLoading = false;\n+ });\n+ case EIntegrationsActions.LoadIntegrationDetails:\n+ return produce(state, draftState => {\n+ draftState.detailed.isLoading = true;\n+ });\n+ case EIntegrationsActions.LoadIntegrationDetailsSuccess:\n+ return produce(state, draftState => {\n+ draftState.detailed.data = action.payload;\n+ draftState.detailed.isLoading = false;\n+ });\n+ case EIntegrationsActions.LoadIntegrationDetailsFailed:\n+ return produce(state, draftState => {\n+ draftState.detailed.isLoading = false;\n+ });\n \n- default: return state;\n+ default: return state;\n }\n };", "status": "modified"}, {"additions": 90, "deletions": 0, "filename": "frontend/src/public/redux/integrations/saga.test.ts", "patch": "@@ -0,0 +1,90 @@\n+import { call, put } from 'redux-saga/effects';\n+import { fetchApiKeys, handleCreateApiKey, handleDeleteApiKey } from './saga';\n+import {\n+ loadApiKeysSuccess,\n+ loadApiKeysFailed,\n+ createApiKeySuccess,\n+ createApiKeyFailed,\n+ deleteApiKeySuccess,\n+ deleteApiKeyFailed,\n+} from './actions';\n+import { getApiKeys, createApiKey, deleteApiKey } from '../../api/getApiKey';\n+import { NotificationManager } from '../../components/UI/Notifications';\n+\n+jest.mock('../../api/getApiKey');\n+jest.mock('../../components/UI/Notifications');\n+\n+describe('integrations saga', () => {\n+ afterEach(() => {\n+ jest.clearAllMocks();\n+ });\n+\n+ describe('fetchApiKeys', () => {\n+ it('handles success', () => {\n+ const mockApiKeys = [{ id: 1 }];\n+ const generator = fetchApiKeys();\n+\n+ expect(generator.next().value).toEqual(call(getApiKeys));\n+ expect(generator.next(mockApiKeys as any).value).toEqual(put(loadApiKeysSuccess(mockApiKeys as any)));\n+ expect(generator.next().done).toBe(true);\n+ });\n+\n+ it('handles failure', () => {\n+ const error = new Error('error');\n+ const generator = fetchApiKeys();\n+\n+ expect(generator.next().value).toEqual(call(getApiKeys));\n+ expect(generator.throw(error).value).toEqual(put(loadApiKeysFailed()));\n+ expect(NotificationManager.notifyApiError).toHaveBeenCalled();\n+ expect(generator.next().done).toBe(true);\n+ });\n+ });\n+\n+ describe('handleCreateApiKey', () => {\n+ it('handles success', () => {\n+ const mockResponse = { id: 1, key: 'pn_live_123', name: 'Test' };\n+ const action = { type: 'CREATE_API_KEY', payload: { name: 'Test' } } as any;\n+ const generator = handleCreateApiKey(action);\n+\n+ expect(generator.next().value).toEqual(call(createApiKey, 'Test'));\n+ expect(generator.next(mockResponse as any).value).toEqual(\n+ put(createApiKeySuccess({ apiKey: { id: 1, name: 'Test' } as any, rawKey: 'pn_live_123' }))\n+ );\n+ expect(generator.next().done).toBe(true);\n+ });\n+\n+ it('handles failure', () => {\n+ const error = new Error('error');\n+ const action = { type: 'CREATE_API_KEY', payload: { name: 'Test' } } as any;\n+ const generator = handleCreateApiKey(action);\n+\n+ expect(generator.next().value).toEqual(call(createApiKey, 'Test'));\n+ expect(generator.throw(error).value).toEqual(put(createApiKeyFailed()));\n+ expect(NotificationManager.notifyApiError).toHaveBeenCalled();\n+ expect(generator.next().done).toBe(true);\n+ });\n+ });\n+\n+ describe('handleDeleteApiKey', () => {\n+ it('handles success', () => {\n+ const action = { type: 'DELETE_API_KEY', payload: { id: 1 } } as any;\n+ const generator = handleDeleteApiKey(action);\n+\n+ expect(generator.next().value).toEqual(call(deleteApiKey, 1));\n+ expect(generator.next().value).toEqual(put(deleteApiKeySuccess({ id: 1 })));\n+ expect(NotificationManager.success).toHaveBeenCalled();\n+ expect(generator.next().done).toBe(true);\n+ });\n+\n+ it('handles failure', () => {\n+ const error = new Error('error');\n+ const action = { type: 'DELETE_API_KEY', payload: { id: 1 } } as any;\n+ const generator = handleDeleteApiKey(action);\n+\n+ expect(generator.next().value).toEqual(call(deleteApiKey, 1));\n+ expect(generator.throw(error).value).toEqual(put(deleteApiKeyFailed()));\n+ expect(NotificationManager.notifyApiError).toHaveBeenCalled();\n+ expect(generator.next().done).toBe(true);\n+ });\n+ });\n+});", "status": "added"}, {"additions": 55, "deletions": 21, "filename": "frontend/src/public/redux/integrations/saga.ts", "patch": "@@ -1,24 +1,27 @@\n-/* eslint-disable */\n-/* prettier-ignore */\n-import { all, fork, takeEvery, call, put, takeLatest, select } from 'redux-saga/effects';\n-import { getApiKey } from '../../api/getApiKey';\n+import { all, fork, takeEvery, call, put, takeLatest, takeLeading } from 'redux-saga/effects';\n+import { getApiKeys, createApiKey as createApiKeyApi, deleteApiKey as deleteApiKeyApi } from '../../api/getApiKey';\n import { getIntegrationDetails } from '../../api/getIntegrationDetails';\n import { getIntegrations } from '../../api/getIntegrations';\n import { NotificationManager } from '../../components/UI/Notifications';\n import { ERoutes } from '../../constants/routes';\n-import { IIntegrationDetailed, IIntegrationListItem } from '../../types/integrations';\n+import { IApiKeyItem, IIntegrationDetailed, IIntegrationListItem, IApiKeyCreateResponse } from '../../types/integrations';\n import { history } from '../../utils/history';\n import { logger } from '../../utils/logger';\n-import { getUserApiKey } from '../selectors/user';\n import {\n EIntegrationsActions,\n loadIntegrationsListSuccess,\n loadIntegrationDetailsFailed,\n loadIntegrationsListFailed,\n loadIntegrationDetailsSuccess,\n TLoadIntegrationDetails,\n- loadApiKeySuccess,\n- loadApiKeyFailed,\n+ loadApiKeysSuccess,\n+ loadApiKeysFailed,\n+ TCreateApiKey,\n+ createApiKeySuccess,\n+ createApiKeyFailed,\n+ TDeleteApiKey,\n+ deleteApiKeySuccess,\n+ deleteApiKeyFailed,\n } from './actions';\n \n function* fetchIntegrationsList() {\n@@ -55,20 +58,37 @@ function* fetchIntegrationDetails({ payload: { id } }: TLoadIntegrationDetails)\n }\n }\n \n-export function* fetchApiKey() {\n+export function* fetchApiKeys() {\n try {\n- const { data: currentApiKey }: ReturnType = yield select(getUserApiKey);\n- if (currentApiKey) {\n- yield put(loadApiKeySuccess(currentApiKey));\n+ const apiKeys: IApiKeyItem[] = yield call(getApiKeys);\n+ yield put(loadApiKeysSuccess(apiKeys));\n+ } catch (error) {\n+ yield put(loadApiKeysFailed());\n+ NotificationManager.notifyApiError(error, { message: 'integrations.fetch-api-key-error' });\n+ logger.error(error);\n+ }\n+}\n \n- return;\n- }\n+export function* handleCreateApiKey({ payload }: TCreateApiKey) {\n+ try {\n+ const response: IApiKeyCreateResponse = yield call(createApiKeyApi, payload.name || '');\n+ const { token: rawKey, ...apiKeyData } = response;\n+ yield put(createApiKeySuccess({ apiKey: apiKeyData as IApiKeyItem, rawKey }));\n+ } catch (error) {\n+ yield put(createApiKeyFailed());\n+ NotificationManager.notifyApiError(error, { message: 'integrations.create-api-key-error' });\n+ logger.error(error);\n+ }\n+}\n \n- const { token } = yield getApiKey();\n- yield put(loadApiKeySuccess(token));\n+export function* handleDeleteApiKey({ payload }: TDeleteApiKey) {\n+ try {\n+ yield call(deleteApiKeyApi, payload.id);\n+ yield put(deleteApiKeySuccess({ id: payload.id }));\n+ NotificationManager.success({ message: 'integrations.api-key-revoked' });\n } catch (error) {\n- yield put(loadApiKeyFailed());\n- NotificationManager.notifyApiError(error, { message: 'integrations.fetch-api-key-error' });\n+ yield put(deleteApiKeyFailed());\n+ NotificationManager.notifyApiError(error, { message: 'integrations.delete-api-key-error' });\n logger.error(error);\n }\n }\n@@ -81,10 +101,24 @@ export function* watchLoadIntegrationDetails() {\n yield takeEvery(EIntegrationsActions.LoadIntegrationDetails, fetchIntegrationDetails);\n }\n \n-export function* watchFetchApiKey() {\n- yield takeLatest(EIntegrationsActions.LoadApiKey, fetchApiKey);\n+export function* watchFetchApiKeys() {\n+ yield takeLatest(EIntegrationsActions.LoadApiKeys, fetchApiKeys);\n+}\n+\n+export function* watchCreateApiKey() {\n+ yield takeLeading(EIntegrationsActions.CreateApiKey, handleCreateApiKey);\n+}\n+\n+export function* watchDeleteApiKey() {\n+ yield takeEvery(EIntegrationsActions.DeleteApiKey, handleDeleteApiKey);\n }\n \n export function* rootSaga() {\n- yield all([fork(watchFetchApiKey), fork(watchLoadIntegrationsList), fork(watchLoadIntegrationDetails)]);\n+ yield all([\n+ fork(watchFetchApiKeys),\n+ fork(watchCreateApiKey),\n+ fork(watchDeleteApiKey),\n+ fork(watchLoadIntegrationsList),\n+ fork(watchLoadIntegrationDetails),\n+ ]);\n }", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/redux/runWorkflowModal/__tests__/reducer.test.ts", "patch": "@@ -2,7 +2,7 @@\n /* prettier-ignore */\n import { reducer, INIT_STATE } from '../reducer';\n import { openRunWorkflowModal } from '../actions';\n-import { IKickoffClient, EExtraFieldType } from '../../../types/template';\n+import { EExtraFieldType, ITemplateKickoffClient } from '../../../types/template';\n import { makeFieldsetBindingClient, makeFieldsetRuntime } from '../../../__stubs__/fieldsets.factory';\n import { makeExtraField } from '../../../__stubs__/fields.factory';\n \n@@ -22,7 +22,7 @@ describe('runWorkflowModal reducer', () => {\n wfNameTemplate: '',\n };\n \n- const kickoff: IKickoffClient = {\n+ const kickoff: ITemplateKickoffClient = {\n description:\n 'youtube: \\nhttps://www.youtube.com/watch?v=JZRm7NKTPhk\\n loom:\\nhttps://www.loom.com/share/29f210bc12484eaa81ca462381fb4415?t=0\\n 404 loom:\\n\\nhttps://www.loom.com/share/9853f0790ad2408094a3717bfcf4a0c0\\nYoutube 404 :\\n\\nhttps://www.youtube.com/watch?v=D6hIeqZt22g',\n fields: [", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/redux/selectors/template.ts", "patch": "@@ -1,13 +1,13 @@\n import { IApplicationState } from '../../types/redux';\n-import { ITemplateClient, ITemplateTaskClient, IKickoffClient, IExtraField } from '../../types/template';\n+import { ITemplateClient, ITemplateTaskClient, ITemplateKickoffClient, IExtraField } from '../../types/template';\n \n export const getTemplateData = (state: IApplicationState): ITemplateClient => {\n return state.template.data;\n };\n \n export const getTemplateStatus = (state: IApplicationState) => state.template.status;\n \n-export const getKickoff = (state: IApplicationState): IKickoffClient =>\n+export const getKickoff = (state: IApplicationState): ITemplateKickoffClient =>\n state.template.data.kickoff;\n \n export const getKickoffFields = (state: IApplicationState): IExtraField[] =>", "status": "modified"}, {"additions": 9, "deletions": 1, "filename": "frontend/src/public/redux/selectors/user.ts", "patch": "@@ -67,7 +67,15 @@ export const getGroupsStore = ({ groups }: IApplicationState) => groups;\n \n export const getUsers = (state: IApplicationState): TUserListItem[] => state.accounts.users;\n \n-export const getUserApiKey = (state: IApplicationState) => state.integrations.apiKey;\n+export const getUserApiKeys = (state: IApplicationState) => state.integrations.apiKeys;\n+\n+export const getUserApiKey = createSelector(\n+ getUserApiKeys,\n+ (apiKeys) => ({\n+ isLoading: apiKeys.isLoading,\n+ data: apiKeys.data[0]?.prefix || '',\n+ }),\n+);\n \n export const getUserTimezone = (state: IApplicationState): string => state.authUser.timezone;\n ", "status": "modified"}, {"additions": 3, "deletions": 6, "filename": "frontend/src/public/redux/workflows/saga.ts", "patch": "@@ -115,7 +115,7 @@ import { sendWorkflowComment } from '../../api/sendWorkflowComment';\n import { finishWorkflow } from '../../api/finishWorkflow';\n import { editWorkflow, IEditWorkflowResponse } from '../../api/editWorkflow';\n import { getTemplatesTitles, TGetTemplatesTitlesResponse } from '../../api/getTemplatesTitles';\n-import { IKickoffClient, ITemplateResponse, TTemplatePreset } from '../../types/template';\n+import { IRuntimeKickoffClient, ITemplateResponse, TTemplatePreset } from '../../types/template';\n import { getWorkflowLogStore } from '../selectors/workflowLog';\n \n import { TChannelAction } from '../tasks/saga';\n@@ -128,7 +128,6 @@ import { deleteWorkflow } from '../../api/deleteWorkflow';\n import { getTemplate } from '../../api/getTemplate';\n import { getRunnableWorkflow, loadDatasetsMap } from '../../components/TemplateEdit/utils/getRunnableWorkflow';\n import { mapTemplateFieldsetsToRuntime } from '../../utils/mapTemplateFieldsetsToRuntime';\n-import { IFieldsetRuntime } from '../../types/fieldset';\n import { getClonedKickoff } from '../../components/Workflows/WorkflowsGridPage/WorkflowCard/utils/getClonedKickoff';\n import { getWorkflowsCurrentPerformerCounters } from '../../api/getWorkflowsCurrentPerformerCounters';\n import { getWorkflowsStartersCounters } from '../../api/getWorkflowsStartersCounters';\n@@ -640,7 +639,7 @@ export function* cloneWorkflowSaga({\n return;\n }\n \n- const kickoff: IKickoffClient = yield getClonedKickoff(\n+ const kickoff: IRuntimeKickoffClient = yield getClonedKickoff(\n formattedworkflowDetails.kickoff, normalizedTemplate.kickoff,\n );\n \n@@ -649,9 +648,7 @@ export function* cloneWorkflowSaga({\n ...runnableWorkflow,\n name: `${workflowName} (Clone)`,\n kickoff,\n- // TODO (Technical Debt): Sync cloned fieldsets into loadedFieldsets for WorkflowEditPopup modal.\n- // Cast is required due to shared IKickoffClient type usage across editor & runtime contexts.\n- loadedFieldsets: (kickoff.fieldsets || []) as unknown as IFieldsetRuntime[],\n+ loadedFieldsets: kickoff.fieldsets || [],\n }),\n );\n } catch (error) {", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/redux/workflows/slice.ts", "patch": "@@ -13,7 +13,7 @@ import { IDeleteComment } from '../../api/workflows/deleteComment';\n import { IEditComment } from '../../api/workflows/editComment';\n \n import { IStoreWorkflows, IWorkflowLog, IWorkflowsList } from '../../types/redux';\n-import { IKickoffClient, ITemplateTitleBaseWithCount, TTemplatePreset } from '../../types/template';\n+import { IRuntimeKickoffClient, ITemplateTitleBaseWithCount, TTemplatePreset } from '../../types/template';\n import { ITemplateStep } from '../../types/tasks';\n import {\n EWorkflowsLoadingStatus,\n@@ -64,7 +64,7 @@ export const initialWorkflowsFilters: IWorkflowsSettings['values'] = {\n const initialWorkflowEdit = {\n workflow: {\n name: '',\n- kickoff: { description: '', fields: [], fieldsets: [] } as IKickoffClient,\n+ kickoff: { description: '', fields: [], fieldsets: [] } as IRuntimeKickoffClient,\n },\n isWorkflowNameEditing: false,\n isKickoffEditing: false,", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/redux/workflows/types.ts", "patch": "@@ -1,7 +1,7 @@\n \n \n import { ITemplateStep } from '../../types/tasks';\n-import { IKickoffClient, TOrderedFields } from '../../types/template';\n+import { IRuntimeKickoffClient, TOrderedFields } from '../../types/template';\n import { EWorkflowsLogSorting, IWorkflowClient } from '../../types/workflow';\n \n export type TOpenWorkflowLogPopupPayload = {\n@@ -28,7 +28,7 @@ export type TRemoveWorkflowFromListPayload = {\n export type TEditWorkflowPayload = {\n typeChange?: string;\n name?: string;\n- kickoff?: IKickoffClient | null;\n+ kickoff?: IRuntimeKickoffClient | null;\n isUrgent?: boolean;\n dueDate?: string | null;\n workflowId: number;", "status": "modified"}, {"additions": 14, "deletions": 0, "filename": "frontend/src/public/types/integrations.ts", "patch": "@@ -14,6 +14,20 @@ export interface IIntegrationDetailed {\n url: string;\n }\n \n+export interface IApiKeyItem {\n+ id: number;\n+ name: string;\n+ prefix: string;\n+ dateCreated: string;\n+ lastUsedAt: string | null;\n+ expiresAt: string | null;\n+ isActive: boolean;\n+}\n+\n+export interface IApiKeyCreateResponse extends IApiKeyItem {\n+ token: string;\n+}\n+\n export enum EIntegrations {\n Shared = 'shared',\n Zapier = 'zapier',", "status": "modified"}, {"additions": 4, "deletions": 3, "filename": "frontend/src/public/types/redux.ts", "patch": "@@ -13,7 +13,7 @@ import {\n IWorkflowDetailsClient,\n } from './workflow';\n import { ITask, ITaskListItem, ITasksSettings } from './tasks';\n-import { IIntegrationDetailed, IIntegrationListItem } from './integrations';\n+import { IApiKeyItem, IIntegrationDetailed, IIntegrationListItem } from './integrations';\n import { ESettingsTabs } from './profile';\n import { IHighlightsItem, EHighlightsDateFilter } from './highlights';\n import { EDashboardTimeRange, IGettingStartedChecklist } from './dashboard';\n@@ -202,9 +202,10 @@ export interface IStoreNotification {\n }\n \n export interface IIntegrationsStore {\n- apiKey: {\n+ apiKeys: {\n isLoading: boolean;\n- data: string;\n+ data: IApiKeyItem[];\n+ newlyCreatedKey: string | null;\n };\n list: {\n isLoading: boolean;", "status": "modified"}, {"additions": 7, "deletions": 9, "filename": "frontend/src/public/types/template.ts", "patch": "@@ -36,7 +36,7 @@ export interface ITemplate {\n \n export interface ITemplateClient extends Omit {\n tasks: ITemplateTaskClient[];\n- kickoff: IKickoffClient;\n+ kickoff: ITemplateKickoffClient;\n }\n \n export enum ETemplateOwnerRole {\n@@ -69,7 +69,7 @@ export type TTransformedTask = {\n \n \n export type TTemplateFieldFieldset = Pick<\n- IFieldsetRuntime, 'name' | 'description' | 'apiNameBinding' | 'fields' | 'order' | 'labelPosition'\n+ IFieldsetRuntime, 'name' | 'title' | 'description' | 'apiNameBinding' | 'fields' | 'order' | 'labelPosition'\n >;\n \n export interface ITemplateTask {\n@@ -237,16 +237,14 @@ export interface IKickoff {\n fieldsets: IFieldsetBinding[];\n }\n \n-/** \n- * TODO (Technical Debt): IKickoffClient is currently shared between Template Editor\n- * (where fieldsets use IFieldsetBindingClient[] with template field definitions) and Workflow\n- * Runtime / Cloning (where fieldsets hold filled values using IFieldsetRuntime[]).\n- * Future refactoring should separate or narrow editor vs runtime kickoff types to avoid type casts.\n- */\n-export interface IKickoffClient extends Omit {\n+export interface ITemplateKickoffClient extends Omit {\n fieldsets: IFieldsetBindingClient[];\n }\n \n+export interface IRuntimeKickoffClient extends Omit {\n+ fieldsets: IFieldsetRuntime[];\n+}\n+\n /** Kickoff shape from template list APIs (GET /templates/, GET /templates/titles-by-owners) */\n export interface IKickoffList {\n fields: {", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/types/workflow.ts", "patch": "@@ -2,7 +2,7 @@ import { TUserId } from './user';\n import { TUploadedFile } from '../utils/uploadFiles';\n import { ITask, ITemplateStep, TaskWithTsp } from './tasks';\n import {\n- IKickoffClient,\n+ IRuntimeKickoffClient,\n IExtraField,\n ITemplateTitle,\n ETemplateOwnerType,\n@@ -73,7 +73,7 @@ export interface IWorkflowDetails {\n \n export interface IWorkflowEditData {\n name?: string;\n- kickoff?: IKickoffClient | null;\n+ kickoff?: IRuntimeKickoffClient | null;\n }\n \n export interface IWorkflowEdit {", "status": "modified"}, {"additions": 16, "deletions": 1, "filename": "frontend/src/public/utils/__tests__/validators.fieldset.test.ts", "patch": "@@ -1,5 +1,5 @@\n \n-import { validateFieldsetName } from '../validators';\n+import { validateFieldsetName, validateFieldsetTitle } from '../validators';\n \n describe('validateFieldsetName', () => {\n it('returns error for empty name', () => {\n@@ -15,3 +15,18 @@ describe('validateFieldsetName', () => {\n expect(validateFieldsetName('a'.repeat(200))).toBe('');\n });\n });\n+\n+describe('validateFieldsetTitle', () => {\n+ it('returns error for empty title', () => {\n+ expect(validateFieldsetTitle('')).toBe('validation.fieldset-title-empty');\n+ });\n+\n+ it('returns error for title longer than 200 characters', () => {\n+ const longTitle = 'a'.repeat(201);\n+ expect(validateFieldsetTitle(longTitle)).toBe('validation.fieldset-title-to-long');\n+ });\n+\n+ it('passes for title exactly 200 characters', () => {\n+ expect(validateFieldsetTitle('a'.repeat(200))).toBe('');\n+ });\n+});", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/utils/mappers.ts", "patch": "@@ -1,4 +1,4 @@\n-import { IExtraField, IKickoffClient } from '../types/template';\n+import { IExtraField, IRuntimeKickoffClient } from '../types/template';\n import { isArrayWithItems } from './helpers';\n import { IRunWorkflow } from '../components/WorkflowEditPopup/types';\n import { ExtraFieldsHelper } from '../components/TemplateEdit/ExtraFields/utils/ExtraFieldsHelper';\n@@ -162,7 +162,7 @@ export const mapEndOfDayTsp = (fields: IExtraField[]): IExtraField[] => {\n }));\n };\n \n-export const getNormalizedKickoff = (kickoff: Pick): { [key: string]: string } => {\n+export const getNormalizedKickoff = (kickoff: Pick): { [key: string]: string } => {\n const mappedKickoffFields = new ExtraFieldsHelper(kickoff.fields).normalizeFieldsValues();\n const mappedKickoff = isArrayWithItems(mappedKickoffFields) ? Object.assign({}, ...mappedKickoffFields) : null;\n return mappedKickoff;", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/utils/template.ts", "patch": "@@ -2,7 +2,7 @@ import {\n ITemplate,\n ITemplateClient,\n ITemplateTaskClient,\n- IKickoffClient,\n+ ITemplateKickoffClient,\n ITemplateRequest,\n ITemplateTaskRequest,\n ITemplateResponse,\n@@ -44,7 +44,7 @@ export function getTemplateIdFromUrl(url: string) {\n return Number(template) ? template : null;\n }\n \n-export function getEmptyKickoff(): IKickoffClient {\n+export function getEmptyKickoff(): ITemplateKickoffClient {\n return {\n description: '',\n fields: [],", "status": "modified"}, {"additions": 12, "deletions": 0, "filename": "frontend/src/public/utils/validators.ts", "patch": "@@ -297,6 +297,18 @@ export const FIELDSET_NAME_RULES: IRule[] = [\n },\n ];\n export const validateFieldsetName = validateFieldCreator(FIELDSET_NAME_RULES);\n+\n+export const FIELDSET_TITLE_RULES: IRule[] = [\n+ {\n+ message: 'validation.fieldset-title-empty',\n+ isInvalid: isEmpty,\n+ },\n+ {\n+ message: 'validation.fieldset-title-to-long',\n+ isInvalid: (value) => value.length > 200,\n+ },\n+];\n+export const validateFieldsetTitle = validateFieldCreator(FIELDSET_TITLE_RULES);\n export const validateDatasetRow = (value: string, existingItems: string[], excludeValue?: string) => {\n const filtered = excludeValue\n ? existingItems.filter((item) => item.trim().toLowerCase() !== excludeValue.trim().toLowerCase())", "status": "modified"}, {"additions": 3, "deletions": 5, "filename": "frontend/src/public/utils/workflows.ts", "patch": "@@ -1,5 +1,5 @@\n import { EDashboardActivityAction, EWorkflowLogEvent, ECommentType, IWorkflowDetailsKickoff } from '../types/workflow';\n-import { ITemplateTaskClient, IKickoffClient, IExtraField, IFieldsetBindingClient } from '../types/template';\n+import { ITemplateTaskClient, IRuntimeKickoffClient, IExtraField } from '../types/template';\n \n import { isArrayWithItems, deepCopy } from './helpers';\n import { ExtraFieldsHelper } from '../components/TemplateEdit/ExtraFields/utils/ExtraFieldsHelper';\n@@ -53,7 +53,7 @@ export const moveWorkflowField = (a: number, b: number, arr: IExtraField[]) => {\n return copy;\n };\n \n-export const getEditKickoff = (kickoff: IWorkflowDetailsKickoff): IKickoffClient => {\n+export const getEditKickoff = (kickoff: IWorkflowDetailsKickoff): IRuntimeKickoffClient => {\n const kickoffFields = new ExtraFieldsHelper(kickoff.output).getFieldsWithValues();\n const kickoffDescritpiton = kickoff.description || '';\n const kickoffFieldsets = (kickoff.fieldsets || []).map((fieldset) => ({\n@@ -64,9 +64,7 @@ export const getEditKickoff = (kickoff: IWorkflowDetailsKickoff): IKickoffClient\n return {\n description: kickoffDescritpiton,\n fields: kickoffFields,\n- // Safe cast: workflow runtime components & API only consume field values from 'fields'.\n- // Template-only properties (rules & sharedFieldsetId) are ignored during workflow execution.\n- fieldsets: kickoffFieldsets as unknown as IFieldsetBindingClient[],\n+ fieldsets: kickoffFieldsets,\n };\n };\n ", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/server/constants/proxy.ts", "patch": "@@ -12,7 +12,7 @@ export const PROXY_ALLOWED_ROUTES = [\n '/auth/reset-password.*',\n '/auth/change-password',\n '/accounts/invites.*',\n- '/accounts/api-key',\n+ '/accounts/api-keys.*',\n '/auth/resend-verification',\n '/auth/verification.*',\n ];", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "frontend/src/server/server.ts", "patch": "@@ -36,7 +36,7 @@ export function initServer() {\n const { host, port = 8000, formSubdomain, mainPage, firebase } = getConfig();\n \n if (devMode) {\n- app.use(devMiddleware(webpackCompiler));\n+ app.use(devMiddleware(webpackCompiler, { writeToDisk: true }));\n app.use(\n hotMiddleware(webpackCompiler, {\n path: '/__webpack_hmr',", "status": "modified"}], "message": "Merge branch 'master' of github.com:pneumaticapp/pneumaticworkflow into frontend/fieldsets/48741__provide_information_regarding_the_binding_of_the_field_set_to_specific_templates", "sha": "65f918c63f71e5caf43d158d83da6d3e3c5c05c6"}, {"author": "Maria-Lordwill", "date": "2026-08-12T10:14:26Z", "files": [{"additions": 8, "deletions": 4, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.css", "patch": "@@ -70,7 +70,7 @@\n @mixin text-base;\n }\n \n-.settings-textarea {\n+.settings-description {\n padding: 1.2rem 1.6rem;\n width: 100%;\n min-height: 8rem;\n@@ -92,7 +92,7 @@\n }\n }\n \n-.settings-select {\n+.settings-label-position {\n padding: 0.8rem 1.2rem;\n width: fit-content;\n min-width: 20rem;\n@@ -127,7 +127,7 @@\n opacity: 0.55;\n }\n \n-.settings-input {\n+.settings-title {\n padding: 0.8rem 1.2rem;\n width: fit-content;\n min-width: 20rem;\n@@ -141,9 +141,13 @@\n &:focus {\n border-color: var(--pneumatic-color-blue);\n }\n+\n+ &:disabled {\n+ @mixin fieldset-field-readonly;\n+ }\n }\n \n-.settings-input_error {\n+.settings-title_error {\n border-color: var(--pneumatic-color-warning);\n }\n ", "status": "modified"}, {"additions": 6, "deletions": 5, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.tsx", "patch": "@@ -218,7 +218,7 @@ const FieldsetDetails = ({\n NotificationManager.warning({\n message: formatMessage({ id: titleErrorMessageKey }),\n });\n- return;\n+ return false;\n }\n \n if (detailFieldsetChanges.rules) {\n@@ -362,12 +362,13 @@ const FieldsetDetails = ({\n id=\"fieldset-title\"\n type=\"text\"\n className={classNames(\n- styles['settings-input'],\n- Boolean(validateFieldsetTitle(detailFieldset.title)) && styles['settings-input_error'],\n+ styles['settings-title'],\n+ Boolean(validateFieldsetTitle(detailFieldset.title)) && styles['settings-title_error'],\n )}\n value={detailFieldset.title}\n placeholder={formatMessage({ id: 'fieldsets.settings.title-placeholder' })}\n onChange={handleSettingsTitleChange}\n+ disabled={isLinked}\n />\n
\n \n@@ -385,7 +386,7 @@ const FieldsetDetails = ({\n \n \n {\n expect(select).toHaveValue('left');\n });\n \n+ // --- Новые тесты: синхронизация и редактирование Title ---\n+\n+ it('синхронизирует title из fieldset', () => {\n+ // title из стора отображается в input\n+ renderWithState(makeLoadedState({ title: 'Custom Title' }));\n+ const input = screen.getByLabelText(formatMsg('fieldsets.settings.title'));\n+ expect(input).toHaveValue('Custom Title');\n+ });\n+\n+ it('активирует Save после изменения title', () => {\n+ // аналог теста для description — новый хендлер handleSettingsTitleChange\n+ renderWithState(makeLoadedState());\n+ const input = screen.getByLabelText(formatMsg('fieldsets.settings.title'));\n+ userEvent.clear(input);\n+ userEvent.type(input, 'New Title');\n+ expect(screen.getByRole('button', { name: SAVE_LABEL })).not.toBeDisabled();\n+ expect(screen.getByText(UNSAVED_HINT)).toBeInTheDocument();\n+ });\n+\n+ it('Save отправляет updateFieldsetAction только с изменённым title', () => {\n+ // payload содержит только title, без description/fields/rules\n+ renderWithState(makeLoadedState({ id: 10, title: 'Old' }));\n+ const input = screen.getByLabelText(formatMsg('fieldsets.settings.title'));\n+ userEvent.clear(input);\n+ userEvent.type(input, 'New');\n+\n+ userEvent.click(screen.getByRole('button', { name: SAVE_LABEL }));\n+\n+ expect(getUpdateActionMock()).toHaveBeenCalledTimes(1);\n+ expect(mockDispatch).toHaveBeenCalledWith(\n+ updateFieldsetAction(\n+ expect.objectContaining({\n+ id: 10,\n+ title: 'New',\n+ }),\n+ ),\n+ );\n+ expect(getUpdateActionMock().mock.calls[0][0]).not.toHaveProperty('description');\n+ expect(getUpdateActionMock().mock.calls[0][0]).not.toHaveProperty('fields');\n+ expect(getUpdateActionMock().mock.calls[0][0]).not.toHaveProperty('rules');\n+ });\n+\n+ it('показывает warning и не отправляет PATCH при пустом title', () => {\n+ // validateFieldsetTitle вернёт ключ ошибки для пустой строки\n+ renderWithState(makeLoadedState({ id: 10, title: 'X' }));\n+ const input = screen.getByLabelText(formatMsg('fieldsets.settings.title'));\n+ userEvent.clear(input);\n+\n+ userEvent.click(screen.getByRole('button', { name: SAVE_LABEL }));\n+\n+ expect(NotificationManager.warning).toHaveBeenCalledTimes(1);\n+ expect(NotificationManager.warning).toHaveBeenCalledWith(\n+ expect.objectContaining({ message: formatMsg('validation.fieldset-title-empty') }),\n+ );\n+ expect(getUpdateActionMock()).not.toHaveBeenCalled();\n+ });\n+\n it('enables Save after changing description', () => {\n renderWithState(makeLoadedState());\n const textarea = screen.getByLabelText(formatMsg('fieldsets.settings.description'));\n@@ -779,6 +836,12 @@ describe('FieldsetDetails', () => {\n \n expect(getModifyDropdownProps().isReadOnly).toBe(true);\n });\n+\n+ it('рендерит not-linked баннер при пустом usage', () => {\n+ // при usage=[] отображается текст \"не привязан\"\n+ renderWithState(makeLoadedState());\n+ expect(screen.getByText(formatMsg('fieldsets.usage.not-linked'))).toBeInTheDocument();\n+ });\n });\n \n describe('handleSave return status (boolean)', () => {\n@@ -788,10 +851,93 @@ describe('FieldsetDetails', () => {\n userEvent.click(screen.getByRole('button', { name: new RegExp(ADD_RULE_TEXT, 'i') }));\n userEvent.click(screen.getByRole('button', { name: SAVE_LABEL }));\n \n+ expect(NotificationManager.warning).toHaveBeenCalledTimes(1);\n expect(NotificationManager.warning).toHaveBeenCalledWith(\n expect.objectContaining({ message: formatMsg(FIELDSET_RULES_MSG_INCOMPLETE) }),\n );\n expect(getUpdateActionMock()).not.toHaveBeenCalled();\n });\n });\n+\n+ // --- Новый блок: Readonly mode при привязке филдсета (isLinked = usage.length > 0) ---\n+ // Проверяем, что при наличии usage все редактируемые элементы заблокированы\n+ describe('Readonly mode когда филдсет привязан к шаблонам', () => {\n+ const LINKED_USAGE = [{ id: 1, name: 'Template 1' }];\n+\n+ it('Settings Title disabled при isLinked', () => {\n+ // input для title должен быть disabled\n+ renderWithState(makeLoadedState({ title: 'Custom', usage: LINKED_USAGE }));\n+ const input = screen.getByLabelText(formatMsg('fieldsets.settings.title'));\n+ expect(input).toBeDisabled();\n+ });\n+\n+ it('Settings Description disabled при isLinked', () => {\n+ // textarea для description должен быть disabled\n+ renderWithState(makeLoadedState({ usage: LINKED_USAGE }));\n+ const textarea = screen.getByLabelText(formatMsg('fieldsets.settings.description'));\n+ expect(textarea).toBeDisabled();\n+ });\n+\n+ it('Settings Label Position disabled при isLinked', () => {\n+ // select для labelPosition должен быть disabled\n+ renderWithState(makeLoadedState({ usage: LINKED_USAGE }));\n+ const select = screen.getByLabelText(formatMsg('fieldsets.settings.label-position'));\n+ expect(select).toBeDisabled();\n+ });\n+\n+ it('Save bar скрыт при isLinked', () => {\n+ // кнопка Save не должна рендериться\n+ renderWithState(makeLoadedState({ usage: LINKED_USAGE }));\n+ expect(screen.queryByRole('button', { name: SAVE_LABEL })).not.toBeInTheDocument();\n+ });\n+\n+ it('Add Rule кнопка скрыта при isLinked', () => {\n+ // кнопка добавления правила не рендерится\n+ renderWithState(makeLoadedState({ usage: LINKED_USAGE }));\n+ expect(screen.queryByRole('button', { name: new RegExp(ADD_RULE_TEXT, 'i') })).not.toBeInTheDocument();\n+ });\n+\n+ it('Rule delete кнопка скрыта при isLinked', () => {\n+ // кнопка удаления правила не рендерится (условный рендер !isLinked)\n+ const rules = [makeFieldsetTemplateRule({ apiName: 'rule-1', value: '100', fields: ['f1'] })];\n+ const fields = [makeField({ apiName: 'f1', order: 1 })];\n+ renderWithState(makeLoadedState({ fields, rules, usage: LINKED_USAGE }));\n+ expect(screen.queryByText(RULE_DELETE_TEXT)).not.toBeInTheDocument();\n+ });\n+\n+ it('Rule inputs disabled при isLinked', () => {\n+ // value input и type select правила disabled\n+ const rules = [makeFieldsetTemplateRule({ apiName: 'rule-1', value: '100', fields: ['f1'] })];\n+ const fields = [makeField({ apiName: 'f1', order: 1 })];\n+ renderWithState(makeLoadedState({ fields, rules, usage: LINKED_USAGE }));\n+\n+ const ruleValueInput = screen.getByDisplayValue('100');\n+ expect(ruleValueInput).toBeDisabled();\n+\n+ // type select тоже disabled\n+ const ruleTypeSelect = screen.getByDisplayValue(formatMsg('fieldsets.rule-type-sum_equal'));\n+ expect(ruleTypeSelect).toBeDisabled();\n+ });\n+\n+ it('ExtraFieldIntl получает isDisabled=true при isLinked', () => {\n+ // wrapper-подход: проверяем prop isDisabled через mock.calls\n+ const fields = [makeField({ apiName: 'f1', order: 1 })];\n+ renderWithState(makeLoadedState({ fields, usage: LINKED_USAGE }));\n+\n+ const mock = getExtraFieldIntlMock();\n+ const lastCall = mock.mock.calls[mock.mock.calls.length - 1];\n+ expect(lastCall[0].isDisabled).toBe(true);\n+ });\n+\n+ it('FilterSelect получает isDisabled=true при isLinked', () => {\n+ // wrapper-подход: проверяем prop isDisabled через mock.calls\n+ const rules = [makeFieldsetTemplateRule({ apiName: 'rule-1', value: '100', fields: ['f1'] })];\n+ const fields = [makeField({ apiName: 'f1', order: 1 })];\n+ renderWithState(makeLoadedState({ fields, rules, usage: LINKED_USAGE }));\n+\n+ const mock = getFilterSelectMock();\n+ const lastCall = mock.mock.calls[mock.mock.calls.length - 1];\n+ expect(lastCall[0].isDisabled).toBe(true);\n+ });\n+ });\n });", "status": "modified"}, {"additions": 17, "deletions": 17, "filename": "frontend/src/public/components/TemplateEdit/ExtraFields/Creatable/ExtraFieldCreatable.css", "patch": "@@ -9,11 +9,11 @@\n padding-top: 1.1rem !important;\n padding-bottom: 1.1rem !important;\n font-family: Nunito, sans-serif;\n- font-size: 15px;\n- line-height: 20px;\n+ font-size: 1.5rem;\n+ line-height: 2rem;\n color: #262522;\n border-color: #dcdcdb !important;\n- border-radius: 8px !important;\n+ border-radius: 0.8rem !important;\n outline: none;\n transition: 0.15s ease-in border-color;\n \n@@ -70,15 +70,15 @@\n \n .kickoff-create-field-container {\n flex-grow: 1;\n- max-width: calc(100% - 40px);\n+ max-width: calc(100% - 4rem);\n \n .measure {\n position: absolute;\n top: -99999px;\n left: -99999px;\n font-family: Nunito, sans-serif;\n- font-size: 15.04px;\n- line-height: 16px;\n+ font-size: 1.504rem;\n+ line-height: 1.6rem;\n white-space: pre;\n }\n }\n@@ -95,8 +95,8 @@\n }\n \n .kickoff-create-field-name-input {\n- margin-bottom: 8px;\n- max-width: calc(100% - 5px);\n+ margin-bottom: 0.8rem;\n+ max-width: calc(100% - 0.5rem);\n border: none;\n \n &:focus {\n@@ -117,7 +117,7 @@\n }\n \n .kickoff-create-field-option {\n- margin: 0 0 8px;\n+ margin: 0 0 0.8rem;\n display: flex;\n align-items: flex-start;\n flex-flow: column;\n@@ -131,12 +131,12 @@\n }\n \n .kickoff-create-field-option__remove {\n- margin-left: 8px;\n+ margin-left: 0.8rem;\n cursor: pointer;\n }\n \n .kickoff-create-field-option__input {\n- max-width: calc(100% - 24px);\n+ max-width: calc(100% - 2.4rem);\n border: none;\n @mixin text-truncate;\n \n@@ -165,8 +165,8 @@\n \n .kickoff-set-field-name {\n position: relative;\n- margin-bottom: 8px;\n- padding-right: 7px;\n+ margin-bottom: 0.8rem;\n+ padding-right: 0.7rem;\n display: inline-block;\n color: var(--pneumatic-color-black72);\n }\n@@ -178,16 +178,16 @@\n }\n \n .kickoff-set-field-option {\n- margin: 0 0 8px;\n+ margin: 0 0 0.8rem;\n display: flex;\n align-items: center;\n }\n \n .kickoff-create-field__error-text {\n- margin-top: 4px;\n+ margin-top: 0.4rem;\n margin-bottom: 0;\n font-family: Nunito, sans-serif;\n- font-size: 13px;\n- line-height: 16px;\n+ font-size: 1.3rem;\n+ line-height: 1.6rem;\n color: #fc5b67;\n }", "status": "modified"}, {"additions": 17, "deletions": 17, "filename": "frontend/src/public/components/UI/Dropdown/Dropdown.css", "patch": "@@ -1,6 +1,6 @@\n .container {\n position: relative;\n- line-height: 20px;\n+ line-height: 2rem;\n }\n \n .dropdown-toggle {\n@@ -18,19 +18,19 @@\n \n .dropdown-menu {\n z-index: 1000;\n- padding: 5px 0;\n+ padding: 0.5rem 0;\n display: none;\n- width: 192px;\n- font-size: 15px;\n+ width: 19.2rem;\n+ font-size: 1.5rem;\n font-weight: initial;\n background: white;\n border: none;\n- border-radius: 8px;\n- box-shadow: 0 8px 16px rgb(98 98 95 / 8%);\n+ border-radius: 0.8rem;\n+ box-shadow: 0 0.8rem 1.6rem rgb(98 98 95 / 8%);\n \n &.is-user-selection {\n /* stylelint-disable-next-line declaration-no-important */\n- top: -5px !important;\n+ top: -0.5rem !important;\n padding: 0;\n }\n }\n@@ -46,7 +46,7 @@\n }\n \n .dropdown-menu_wide {\n- width: 304px;\n+ width: 30.4rem;\n }\n \n .dropdown-menu_show {\n@@ -57,7 +57,7 @@\n .dropdown-item {\n position: relative;\n z-index: 1;\n- padding: 5px 16px;\n+ padding: 0.5rem 1.6rem;\n display: flex;\n width: 100%;\n text-align: inherit;\n@@ -70,13 +70,13 @@\n &::before {\n position: absolute;\n z-index: -1;\n- top: -1px;\n- right: 4px;\n- left: 4px;\n- bottom: -1px;\n+ top: -0.1rem;\n+ right: 0.4rem;\n+ left: 0.4rem;\n+ bottom: -0.1rem;\n content: '';\n background: var(--pneumatic-color-beige);\n- border-radius: 4px;\n+ border-radius: 0.4rem;\n opacity: 0;\n }\n \n@@ -94,7 +94,7 @@\n }\n \n .dropdown-item-tooltip {\n- padding: 4px 8px;\n+ padding: 0.4rem 0.8rem;\n text-align: center;\n }\n \n@@ -152,10 +152,10 @@\n \n .line {\n all: unset;\n- margin: 5px 12px;\n+ margin: 0.5rem 1.2rem;\n display: block;\n border: 0;\n- border-top: 1px solid var(--pneumatic-color-black16);\n+ border-top: 0.1rem solid var(--pneumatic-color-black16);\n }\n \n .dropdown-confirm {", "status": "modified"}], "message": "48741 feat(fieldsets): add title readonly support, expand test coverage, convert px to rem", "sha": "13c1354c68d855efd2ef5a4ed670b805b83933dd"}, {"author": "Maria-Lordwill", "date": "2026-08-13T05:12:22Z", "files": [{"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.css", "patch": "@@ -62,10 +62,10 @@\n }\n \n .settings-label {\n- font-weight: 600;\n- color: var(--pneumatic-color-black72);\n display: flex;\n gap: 0.4rem;\n+ font-weight: 600;\n+ color: var(--pneumatic-color-black72);\n \n @mixin text-base;\n }", "status": "modified"}, {"additions": 2, "deletions": 4, "filename": "frontend/src/public/components/TemplateEdit/KickoffRedux/KickoffRedux.tsx", "patch": "@@ -116,8 +116,8 @@ export function KickoffRedux({\n if (rows) saveOutputOrders(rows);\n };\n \n- const handleRemoveFieldset = (sharedFieldsetId: number) => {\n- const rows = buildRowsWithRemovedFieldset(kickoff.fields, kickoff.fieldsets || [], sharedFieldsetId);\n+ const handleRemoveFieldset = (apiNameBinding: string) => {\n+ const rows = buildRowsWithRemovedFieldset(kickoff.fields, kickoff.fieldsets || [], apiNameBinding);\n saveOutputOrders(rows);\n };\n const handleDeleteField = (apiName: string) => {\n@@ -173,9 +173,7 @@ export function KickoffRedux({\n ))}\n fieldset.sharedFieldsetId)}\n onSelectFieldset={handleAddKickoffFieldset}\n- onRemoveFieldset={handleRemoveFieldset}\n />\n
\n {!isFormEmpty && (", "status": "modified"}, {"additions": 7, "deletions": 4, "filename": "frontend/src/public/components/TemplateEdit/OutputForm/OutputForm.css", "patch": "@@ -85,18 +85,22 @@\n }\n \n .flow__fieldset-title-edit {\n- display: inline-flex;\n- align-items: center;\n margin-top: 0.2rem;\n padding-left: 1.2rem;\n+ display: inline-flex;\n+ align-items: center;\n gap: 0.4rem;\n \n @mixin text-small;\n }\n \n+.flow__fieldset-row {\n+ min-height: 2rem;\n+}\n+\n .flow__fieldset-title-input {\n- border: none;\n resize: none;\n+ border: none;\n outline: none;\n field-sizing: content;\n \n@@ -110,4 +114,3 @@\n color: var(--pneumatic-color-warning);\n }\n }\n-", "status": "modified"}, {"additions": 2, "deletions": 4, "filename": "frontend/src/public/components/TemplateEdit/OutputForm/OutputFormTaskMerged.tsx", "patch": "@@ -124,8 +124,8 @@ export function OutputFormTaskMerged({\n );\n \n const handleRemoveFieldset = useCallback(\n- (sharedFieldsetId: number) => {\n- const rows = buildRowsWithRemovedFieldset(task.fields || [], task.fieldsets || [], sharedFieldsetId);\n+ (apiNameBinding: string) => {\n+ const rows = buildRowsWithRemovedFieldset(task.fields || [], task.fieldsets || [], apiNameBinding);\n saveOutputOrders(rows).catch(() => undefined);\n },\n [saveOutputOrders, task.fieldsets, task.fields],\n@@ -152,9 +152,7 @@ export function OutputFormTaskMerged({\n ))}\n fieldset.sharedFieldsetId)}\n onSelectFieldset={handleAddFieldset}\n- onRemoveFieldset={handleRemoveFieldset}\n />\n
\n ", "status": "modified"}, {"additions": 18, "deletions": 20, "filename": "frontend/src/public/components/TemplateEdit/OutputForm/__tests__/OutputFormTaskMerged.test.tsx", "patch": "@@ -41,9 +41,7 @@ jest.mock('../../ExtraFields/utils/ExtraFieldIcon', () => ({\n \n jest.mock('../../TaskOutputFlow/FieldsetIconPicker', () => ({\n FieldsetIconPicker: (props: {\n- selectedFieldsetIds: number[];\n onSelectFieldset: (item: IFieldsetCatalogItem) => void;\n- onRemoveFieldset: (sharedFieldsetId: number) => void;\n }) => {\n const catalogItems = (getFieldsetsCatalogItems as jest.Mock)();\n return React.createElement(\n@@ -60,17 +58,6 @@ jest.mock('../../TaskOutputFlow/FieldsetIconPicker', () => ({\n `Add fieldset ${item.name}`,\n ),\n ),\n- props.selectedFieldsetIds.map((id: number) =>\n- React.createElement(\n- 'button',\n- {\n- key: `remove-${id}`,\n- type: 'button',\n- onClick: () => props.onRemoveFieldset(id),\n- },\n- `Remove fieldset ${id}`,\n- ),\n- ),\n );\n },\n }));\n@@ -79,12 +66,12 @@ jest.mock('../../TaskOutputFlow/MergedOutputRows', () => ({\n MergedOutputRows: (props: {\n mergedRows: Array<\n | { kind: 'field'; field: IExtraField }\n- | { kind: 'fieldset'; apiName: string; order: number }\n+ | { kind: 'fieldset'; apiNameBinding: string; sharedFieldsetId?: number }\n >;\n onDeleteField: (apiName: string) => void;\n onMoveRow: (index: number, direction: 'up' | 'down') => void;\n onEditField: (apiName: string) => (changed: Partial) => void;\n- onRemoveFieldset: (apiName: string) => void;\n+ onRemoveFieldset: (apiNameBinding: string) => void;\n }) =>\n React.createElement(\n 'div',\n@@ -120,9 +107,18 @@ jest.mock('../../TaskOutputFlow/MergedOutputRows', () => ({\n ),\n );\n }\n+ const apiNameBinding = row.apiNameBinding;\n return React.createElement(\n 'div',\n- { key: `fieldset-${row.apiName}` },\n+ { key: `fieldset-${apiNameBinding}` },\n+ React.createElement(\n+ 'button',\n+ {\n+ type: 'button',\n+ onClick: () => props.onRemoveFieldset(apiNameBinding),\n+ },\n+ `Remove fieldset ${apiNameBinding}`,\n+ ),\n React.createElement(\n 'button',\n { type: 'button', onClick: () => props.onMoveRow(index, 'up') },\n@@ -277,7 +273,7 @@ describe('OutputFormTaskMerged', () => {\n expect(arg.changedFields.fieldsets).toBeDefined();\n });\n \n- it('does not send PATCH when adding an already-connected fieldset', () => {\n+ it('allows adding an already-connected fieldset and sends PATCH with a new fieldset binding', () => {\n const catalogItem = makeFieldsetCatalogItem({ id: 1, apiName: 'fs-1', name: 'Fieldset 1' });\n const { patchTask } = renderForm({\n task: makeTask({ fields: [], fieldsets: [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 0, sharedFieldsetId: 1 })] }),\n@@ -286,21 +282,23 @@ describe('OutputFormTaskMerged', () => {\n \n userEvent.click(screen.getByRole('button', { name: 'Add fieldset Fieldset 1' }));\n \n- expect(patchTask).not.toHaveBeenCalled();\n+ expect(patchTask).toHaveBeenCalledTimes(1);\n+ const arg = patchTask.mock.calls[0][0];\n+ expect(arg.changedFields.fieldsets).toHaveLength(2);\n });\n \n it('removing a fieldset sends PATCH without it and recomputes order of remaining ones', () => {\n const { patchTask } = renderForm({\n task: makeTask({\n fields: [],\n fieldsets: [\n- makeFieldsetBindingClient({ apiNameBinding: 'fs-a', order: 0, sharedFieldsetId: 10 }),\n+ makeFieldsetBindingClient({ apiNameBinding: 'fs-a', order: 0, sharedFieldsetId: 10 }),\n makeFieldsetBindingClient({ apiNameBinding: 'fs-b', order: 1, sharedFieldsetId: 20 }),\n ],\n }),\n });\n \n- userEvent.click(screen.getByRole('button', { name: 'Remove fieldset 10' }));\n+ userEvent.click(screen.getByRole('button', { name: 'Remove fieldset fs-a' }));\n \n expect(patchTask).toHaveBeenCalledTimes(1);\n const arg = patchTask.mock.calls[0][0];", "status": "modified"}, {"additions": 2, "deletions": 0, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/FieldsetEditorTitle.tsx", "patch": "@@ -59,6 +59,8 @@ export function FieldsetEditorTitle({\n />\n {!isFocused && (\n inputRef.current?.focus()}\n className={kickoffStyles['kick-off-edit-name']}\n >", "status": "modified"}, {"additions": 7, "deletions": 39, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/FieldsetIconPicker.css", "patch": "@@ -1,29 +1,14 @@\n-.fieldset-picker__option {\n- padding: 0.8rem 1.6rem;\n- display: flex;\n- width: 100%;\n- font-family: Nunito, sans-serif;\n- font-size: 1.4rem;\n- line-height: 2rem;\n- text-align: left;\n- cursor: pointer;\n- color: var(--pneumatic-color-black100);\n- background: none;\n- border: none;\n- transition: background-color 0.1s ease;\n- align-items: center;\n+.fieldset-picker__container,\n+.fieldset-picker__toggle {\n+ padding: 0;\n }\n \n-.fieldset-picker__option:hover {\n- background-color: var(--pneumatic-color-beige);\n+.fieldset-picker__arrow_hidden {\n+ display: none;\n }\n \n-.fieldset-picker__checkbox {\n- margin-right: 1.2rem;\n- width: 1.6rem;\n- height: 1.6rem;\n- flex-shrink: 0;\n- accent-color: var(--pneumatic-color-link);\n+.fieldset-picker__menu {\n+ max-width: 20rem;\n }\n \n .fieldset-picker__option-info {\n@@ -44,20 +29,3 @@\n line-height: 1.6rem;\n color: var(--pneumatic-color-black48);\n }\n-\n-.fieldset-picker__empty {\n- padding: 1.6rem;\n- font-family: Nunito, sans-serif;\n- font-size: 1.3rem;\n- line-height: 2rem;\n- text-align: center;\n- color: var(--pneumatic-color-black48);\n-}\n-\n-.fieldset-picker__loading {\n- padding: 1.6rem;\n- font-family: Nunito, sans-serif;\n- font-size: 1.3rem;\n- text-align: center;\n- color: var(--pneumatic-color-black48);\n-}", "status": "modified"}, {"additions": 53, "deletions": 85, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/FieldsetIconPicker.tsx", "patch": "@@ -1,19 +1,25 @@\n import * as React from 'react';\n-import { useCallback, useMemo, useRef } from 'react';\n+import { ReactNode, useCallback, useMemo, useRef } from 'react';\n import { useIntl } from 'react-intl';\n import { useSelector } from 'react-redux';\n-import classNames from 'classnames';\n \n import { IFieldsetCatalogItem } from '../../../types/fieldset';\n import { getFieldsetsCatalogItems } from '../../../redux/selectors/fieldsets';\n import { CustomTooltip } from '../../UI/CustomTooltip';\n-import { Dropdown, type TDropdownOption } from '../../UI';\n+import { FilterSelect } from '../../UI';\n import { FieldsetIcon } from '../../icons/FieldsetIcon';\n \n import pickerStyles from './FieldsetIconPicker.css';\n import kickoffStyles from '../KickoffRedux/KickoffRedux.css';\n import flowStyles from '../OutputForm/OutputForm.css';\n \n+interface IFieldsetCatalogOption {\n+ id: number;\n+ name: string;\n+ label: ReactNode;\n+ searchByText: string;\n+}\n+\n interface IFieldsetCatalogPickerRow {\n id: number;\n apiName: string;\n@@ -25,9 +31,7 @@ interface IFieldsetCatalogPickerRow {\n \n export interface IFieldsetIconPickerProps {\n fieldsetsCatalogLoading: boolean;\n- selectedFieldsetIds: number[];\n onSelectFieldset: (fieldsetCatalogItem: IFieldsetCatalogItem) => void;\n- onRemoveFieldset: (sharedFieldsetId: number) => void;\n }\n \n const buildCatalogPickerRows = (catalogFieldsetItems: IFieldsetCatalogItem[]): IFieldsetCatalogPickerRow[] => {\n@@ -50,112 +54,76 @@ const buildCatalogPickerRows = (catalogFieldsetItems: IFieldsetCatalogItem[]): I\n \n export const FieldsetIconPicker = ({\n fieldsetsCatalogLoading,\n- selectedFieldsetIds,\n onSelectFieldset,\n- onRemoveFieldset,\n }: IFieldsetIconPickerProps) => {\n const { formatMessage } = useIntl();\n const triggerRef = useRef(null);\n const fieldsetsCatalogItems = useSelector(getFieldsetsCatalogItems);\n \n- const catalogRows = useMemo(() => buildCatalogPickerRows(fieldsetsCatalogItems), [fieldsetsCatalogItems]);\n- const showListLoading = fieldsetsCatalogLoading && catalogRows.length === 0;\n+ const options = useMemo((): IFieldsetCatalogOption[] => {\n+ const rows = buildCatalogPickerRows(fieldsetsCatalogItems);\n+ return rows.map((row) => ({\n+ id: row.id,\n+ name: row.name,\n+ searchByText: row.name,\n+ label: (\n+
\n+ {row.name}\n+ \n+ {row.fieldsCount} fields · {row.rulesCount} rules\n+ \n+
\n+ ),\n+ }));\n+ }, [fieldsetsCatalogItems]);\n \n- const handleToggleFieldset = useCallback(\n- (sharedFieldsetId: number) => {\n- if (selectedFieldsetIds.includes(sharedFieldsetId)) {\n- onRemoveFieldset(sharedFieldsetId);\n- return;\n- }\n+ const handleSelectFieldset = useCallback(\n+ (sharedFieldsetId: number | null) => {\n+ if (sharedFieldsetId === null) return;\n const fieldsetCatalogItem = fieldsetsCatalogItems.find((item) => item.id === sharedFieldsetId);\n if (fieldsetCatalogItem) {\n onSelectFieldset(fieldsetCatalogItem);\n }\n },\n- [fieldsetsCatalogItems, onRemoveFieldset, onSelectFieldset, selectedFieldsetIds],\n+ [fieldsetsCatalogItems, onSelectFieldset],\n );\n \n- const catalogDropdownOption = useMemo((): TDropdownOption => {\n- return {\n- mapKey: 'template.fieldset-icon-picker.catalog',\n- label: '\\u00a0',\n- customSubOption: (\n-
\n- {showListLoading ? (\n-
\n- {formatMessage({ id: 'template.fieldset-picker.loading', defaultMessage: 'Loading…' })}\n-
\n- ) : null}\n-\n- {!showListLoading && catalogRows.length === 0 ? (\n-
\n- {formatMessage({ id: 'template.fieldset-picker.empty' })}\n-
\n- ) : null}\n-\n- {!showListLoading\n- && catalogRows.map((row) => {\n- const isSelected = selectedFieldsetIds.includes(row.id);\n- return (\n- handleToggleFieldset(row.id)}\n- id={`task-output-fieldset-option-${row.id}`}\n- >\n- \n-
\n- {row.name}\n- \n- {row.fieldsCount} fields · {row.rulesCount} rules\n- \n-
\n- \n- );\n- })}\n-
\n- ),\n- };\n- }, [\n- catalogRows,\n- formatMessage,\n- handleToggleFieldset,\n- selectedFieldsetIds,\n- showListLoading,\n- ]);\n-\n return (\n
\n- (\n+ \n+ optionIdKey=\"id\"\n+ optionLabelKey=\"label\"\n+ options={options}\n+ isLoading={fieldsetsCatalogLoading}\n+ isSearchShown\n+ positionFixed\n+ selectedOption={null}\n+ onChange={handleSelectFieldset}\n+ resetFilter={() => {}}\n+ searchPlaceholder={formatMessage({ id: 'search.placeholder', defaultMessage: 'Search...' })}\n+ placeholderText={formatMessage({ id: 'template.fieldset-picker.empty' })}\n+ containerClassname={pickerStyles['fieldset-picker__container']}\n+ toggleClassName={pickerStyles['fieldset-picker__toggle']}\n+ menuClassName={pickerStyles['fieldset-picker__menu']}\n+ arrowClassName={pickerStyles['fieldset-picker__arrow_hidden']}\n+ renderPlaceholder={() => (\n \n \n \n )}\n- options={catalogDropdownOption}\n />\n- \n+ })}\n+ tooltipTitle={formatMessage({ id: 'fieldsets.title' })}\n+ />\n
\n );\n };\n+", "status": "modified"}, {"additions": 3, "deletions": 3, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/MergedOutputRows.tsx", "patch": "@@ -20,7 +20,7 @@ export interface IMergedOutputRowsProps {\n onDeleteField: (apiName: string) => void;\n onMoveRow: (index: number, direction: 'up' | 'down') => void;\n onEditField: (apiName: string) => (changedProps: Partial) => void;\n- onRemoveFieldset: (sharedFieldsetId: number) => void;\n+ onRemoveFieldset: (apiNameBinding: string) => void;\n datasetOptions: { value: string; label: string }[];\n accountId: number;\n formatMessage: (descriptor: { id: string }) => string;\n@@ -74,6 +74,7 @@ export function MergedOutputRows({\n className={classNames(\n kickoffStyles['with-label'],\n kickoffStyles['kick-off-input'],\n+ styles['flow__fieldset-row'],\n )}\n >\n
\n@@ -93,14 +94,13 @@ export function MergedOutputRows({\n }\n
\n
\n- {/* sharedFieldsetId is synced with FieldsetIconPicker — do not replace with apiNameBinding */}\n onMoveRow(index, 'up')}\n onMoveDown={() => onMoveRow(index, 'down')}\n- onRemove={() => onRemoveFieldset(row.sharedFieldsetId)}\n+ onRemove={() => onRemoveFieldset(row.apiNameBinding)}\n />\n
\n ", "status": "modified"}, {"additions": 44, "deletions": 106, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/__tests__/FieldsetIconPicker.test.tsx", "patch": "@@ -3,16 +3,15 @@ import { render, screen } from '@testing-library/react';\n import userEvent from '@testing-library/user-event';\n import { useSelector } from 'react-redux';\n \n-import { makeExtraField } from '../../../../__stubs__/fields.factory';\n-import { makeFieldsetCatalogItem } from '../../../../__stubs__/fieldsets.factory';\n+import {\n+ makeFieldsetCatalogItem,\n+ makeFieldsetField,\n+ makeFieldsetTemplateRule,\n+} from '../../../../__stubs__/fieldsets.factory';\n import { IFieldsetCatalogItem } from '../../../../types/fieldset';\n import { intlMock } from '../../../../__stubs__/intlMock';\n-import { Dropdown } from '../../../UI';\n-import { IDropdownProps, TDropdownOption } from '../../../UI/Dropdown/Dropdown';\n import { FieldsetIconPicker, IFieldsetIconPickerProps } from '../FieldsetIconPicker';\n-import {\n- getFieldsetsCatalogItems,\n-} from '../../../../redux/selectors/fieldsets';\n+import { getFieldsetsCatalogItems } from '../../../../redux/selectors/fieldsets';\n \n jest.mock('react-redux', () => ({\n useSelector: jest.fn(),\n@@ -23,9 +22,26 @@ jest.mock('../../../../redux/selectors/fieldsets', () => ({\n }));\n \n jest.mock('../../../UI', () => ({\n- Dropdown: jest.fn(({ options }: IDropdownProps) => {\n- const single = !Array.isArray(options) ? (options as TDropdownOption) : null;\n- return single?.customSubOption ?? null;\n+ FilterSelect: jest.fn(({ options, onChange, isLoading, placeholderText }: any) => {\n+ if (isLoading && options.length === 0) {\n+ return
Loading…
;\n+ }\n+ if (options.length === 0) {\n+ return
{placeholderText}
;\n+ }\n+ return (\n+
\n+ {options.map((option: any) => (\n+ onChange(option.id)}\n+ >\n+ {option.label}\n+ \n+ ))}\n+
\n+ );\n }),\n CustomTooltip: () => null,\n }));\n@@ -38,7 +54,6 @@ jest.mock('../../../icons/FieldsetIcon', () => ({\n FieldsetIcon: () => null,\n }));\n \n-\n const makeCatalogItem = (\n id: number,\n apiName: string,\n@@ -51,16 +66,6 @@ const makeCatalogItem = (\n order,\n });\n \n-const getDropdownProps = (): IDropdownProps => {\n- const calls = (Dropdown as jest.Mock).mock.calls;\n- return calls[calls.length - 1][0];\n-};\n-\n-const makeField = (apiName: string) => makeExtraField({\n- apiName,\n- name: `Field ${apiName}`,\n-});\n-\n const formatMsg = (id: string, defaultMessage?: string) =>\n intlMock.formatMessage({ id, defaultMessage });\n \n@@ -69,9 +74,7 @@ const EMPTY_STATE = {};\n describe('FieldsetIconPicker', () => {\n const makeProps = (overrides: Partial = {}): IFieldsetIconPickerProps => ({\n fieldsetsCatalogLoading: false,\n- selectedFieldsetIds: [],\n onSelectFieldset: jest.fn(),\n- onRemoveFieldset: jest.fn(),\n ...overrides,\n });\n \n@@ -83,12 +86,7 @@ describe('FieldsetIconPicker', () => {\n (getFieldsetsCatalogItems as jest.Mock).mockReturnValue([]);\n });\n \n- it('Dropdown does not receive isDisabled prop', () => {\n- render(React.createElement(FieldsetIconPicker, makeProps()));\n- expect(getDropdownProps().isDisabled).toBeUndefined();\n- });\n-\n- it('fieldsetsCatalogLoading=true and empty catalog → loading text is rendered', () => {\n+ it('fieldsetsCatalogLoading=true and empty catalog -> loading text is rendered', () => {\n render(\n React.createElement(\n FieldsetIconPicker,\n@@ -100,7 +98,7 @@ describe('FieldsetIconPicker', () => {\n ).toBeInTheDocument();\n });\n \n- it('fieldsetsCatalogLoading=false and empty catalog → empty text is rendered', () => {\n+ it('fieldsetsCatalogLoading=false and empty catalog -> empty text is rendered', () => {\n render(\n React.createElement(\n FieldsetIconPicker,\n@@ -110,9 +108,7 @@ describe('FieldsetIconPicker', () => {\n expect(screen.getByText(formatMsg('template.fieldset-picker.empty'))).toBeInTheDocument();\n });\n \n- it('renders fieldsets sorted by order property', () => {\n- // Бизнес: филдсеты отображаются в порядке, заданном в каталоге (поле order).\n- // Идентификатор: каталожный id (1, 2, 3). Order определяет визуальный порядок.\n+ it('renders fieldsets sorted by order property ascending', () => {\n const catalogItems: IFieldsetCatalogItem[] = [\n makeCatalogItem(1, 'fs-a', 'Alpha', 2),\n makeCatalogItem(2, 'fs-b', 'Zeta', 0),\n@@ -128,9 +124,8 @@ describe('FieldsetIconPicker', () => {\n expect(buttons[2]).toHaveTextContent('Alpha');\n });\n \n- it('click on unselected fieldset calls onSelectFieldset, onRemoveFieldset not called', () => {\n+ it('click on fieldset option calls onSelectFieldset with fieldset object', () => {\n const onSelectFieldset = jest.fn();\n- const onRemoveFieldset = jest.fn();\n const catalogItems: IFieldsetCatalogItem[] = [\n makeCatalogItem(1, 'fs-1', 'My Fieldset', 0),\n ];\n@@ -140,9 +135,7 @@ describe('FieldsetIconPicker', () => {\n React.createElement(\n FieldsetIconPicker,\n makeProps({\n- selectedFieldsetIds: [],\n onSelectFieldset,\n- onRemoveFieldset,\n }),\n ),\n );\n@@ -151,71 +144,6 @@ describe('FieldsetIconPicker', () => {\n \n expect(onSelectFieldset).toHaveBeenCalledTimes(1);\n expect(onSelectFieldset).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }));\n- expect(onRemoveFieldset).not.toHaveBeenCalled();\n- });\n-\n- it('click on selected fieldset calls onRemoveFieldset, onSelectFieldset not called', () => {\n- const onSelectFieldset = jest.fn();\n- const onRemoveFieldset = jest.fn();\n- const catalogItems: IFieldsetCatalogItem[] = [\n- makeCatalogItem(1, 'fs-1', 'My Fieldset', 0),\n- ];\n- (getFieldsetsCatalogItems as jest.Mock).mockReturnValue(catalogItems);\n-\n- render(\n- React.createElement(\n- FieldsetIconPicker,\n- makeProps({\n- selectedFieldsetIds: [1],\n- onSelectFieldset,\n- onRemoveFieldset,\n- }),\n- ),\n- );\n-\n- userEvent.click(screen.getByRole('button'));\n-\n- expect(onRemoveFieldset).toHaveBeenCalledTimes(1);\n- expect(onRemoveFieldset).toHaveBeenCalledWith(1);\n- expect(onSelectFieldset).not.toHaveBeenCalled();\n- });\n-\n- it('selected fieldset renders checkbox in checked state', () => {\n- const catalogItems: IFieldsetCatalogItem[] = [\n- makeCatalogItem(1, 'fs-1', 'My Fieldset', 0),\n- ];\n- (getFieldsetsCatalogItems as jest.Mock).mockReturnValue(catalogItems);\n-\n- render(\n- React.createElement(\n- FieldsetIconPicker,\n- makeProps({\n- selectedFieldsetIds: [1],\n- }),\n- ),\n- );\n-\n- const checkbox = screen.getByRole('checkbox', { hidden: true });\n- expect(checkbox).toBeChecked();\n- });\n-\n- it('unselected fieldset renders checkbox in unchecked state', () => {\n- const catalogItems: IFieldsetCatalogItem[] = [\n- makeCatalogItem(1, 'fs-1', 'My Fieldset', 0),\n- ];\n- (getFieldsetsCatalogItems as jest.Mock).mockReturnValue(catalogItems);\n-\n- render(\n- React.createElement(\n- FieldsetIconPicker,\n- makeProps({\n- selectedFieldsetIds: [],\n- }),\n- ),\n- );\n-\n- const checkbox = screen.getByRole('checkbox', { hidden: true });\n- expect(checkbox).not.toBeChecked();\n });\n \n it('background catalog load does not show loading text when list is not empty', () => {\n@@ -237,11 +165,21 @@ describe('FieldsetIconPicker', () => {\n expect(screen.getByText('My Set')).toBeInTheDocument();\n });\n \n- it('meta line shows \" fields · rules\" with real numbers', () => {\n+ it('meta line displays fields and rules count using typed stub factories without as any', () => {\n const catalogItem = makeFieldsetCatalogItem({\n name: 'My Set',\n- fields: [makeField('a'), makeField('b'), makeField('c')] as any,\n- rules: [{}, {}, {}, {}, {}] as any,\n+ fields: [\n+ makeFieldsetField({ apiName: 'a' }),\n+ makeFieldsetField({ apiName: 'b' }),\n+ makeFieldsetField({ apiName: 'c' }),\n+ ],\n+ rules: [\n+ makeFieldsetTemplateRule(),\n+ makeFieldsetTemplateRule(),\n+ makeFieldsetTemplateRule(),\n+ makeFieldsetTemplateRule(),\n+ makeFieldsetTemplateRule(),\n+ ],\n });\n (getFieldsetsCatalogItems as jest.Mock).mockReturnValue([catalogItem]);\n \n@@ -250,7 +188,7 @@ describe('FieldsetIconPicker', () => {\n expect(screen.getByText('3 fields · 5 rules')).toBeInTheDocument();\n });\n \n- it('meta line shows \"0 fields · 0 rules\" when fields and rules are empty', () => {\n+ it('meta line displays \"0 fields · 0 rules\" when fields and rules are empty', () => {\n const catalogItem = makeFieldsetCatalogItem({\n name: 'My Set',\n fields: [],", "status": "modified"}, {"additions": 2, "deletions": 2, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/__tests__/MergedOutputRows.test.tsx", "patch": "@@ -161,7 +161,7 @@ describe('MergedOutputRows', () => {\n expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument();\n });\n \n- it('click Remove → onRemoveFieldset(sharedFieldsetId) called once', () => {\n+ it('click Remove → onRemoveFieldset(apiNameBinding) called once', () => {\n const onRemoveFieldset = jest.fn();\n \n render(\n@@ -174,7 +174,7 @@ describe('MergedOutputRows', () => {\n userEvent.click(screen.getByRole('button', { name: 'Remove' }));\n \n expect(onRemoveFieldset).toHaveBeenCalledTimes(1);\n- expect(onRemoveFieldset).toHaveBeenCalledWith(1);\n+ expect(onRemoveFieldset).toHaveBeenCalledWith('fs-1');\n });\n \n it('click Up → onMoveRow(0, \"up\") called once, \"down\" not called', () => {", "status": "modified"}, {"additions": 26, "deletions": 23, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/__tests__/mergeTaskOutputFlow.test.ts", "patch": "@@ -7,18 +7,8 @@ import {\n buildRowsWithRemovedFieldset,\n moveMergedRow,\n normalizeMergedTaskOutputOrders,\n- TMergedTaskOutputRow,\n } from '../mergeTaskOutputFlow';\n \n-const assertRowsDefined = (\n- rows: TMergedTaskOutputRow[] | null,\n-): TMergedTaskOutputRow[] => {\n- if (rows === null) {\n- throw new Error('expected rows to be non-null');\n- }\n- return rows;\n-};\n-\n const field = (apiName: string, order: number) =>\n makeExtraField({ apiName, name: apiName, order });\n \n@@ -84,24 +74,24 @@ describe('mergeTaskOutputFlow', () => {\n });\n \n describe('buildRowsWithAddedFieldset', () => {\n- it('adds fieldset to rows when it is not already present', () => {\n+ it('adds fieldset to rows', () => {\n const result = buildRowsWithAddedFieldset(\n [field('a', 0)],\n [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1 })],\n makeFieldsetBindingClient({ apiNameBinding: 'fs-new', order: 0, sharedFieldsetId: 99 }),\n );\n- const rows = assertRowsDefined(result);\n- const apiNames = rows.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n+ const apiNames = result.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n expect(apiNames).toContain('fs-new');\n });\n \n- it('returns null when fieldset with that apiName is already present', () => {\n+ it('allows adding a second instance of the same sharedFieldsetId with a new apiNameBinding', () => {\n const result = buildRowsWithAddedFieldset(\n [field('a', 0)],\n- [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1 })],\n- makeFieldsetBindingClient({ apiNameBinding: 'fs-1-dup', order: 0, sharedFieldsetId: 1 }),\n+ [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1, sharedFieldsetId: 1 })],\n+ makeFieldsetBindingClient({ apiNameBinding: 'fs-2', order: 0, sharedFieldsetId: 1 }),\n );\n- expect(result).toBeNull();\n+ const apiNames = result.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n+ expect(apiNames).toEqual(expect.arrayContaining(['fs-1', 'fs-2']));\n });\n \n it('places the newly added fieldset as the last row in the merged list', () => {\n@@ -110,34 +100,47 @@ describe('mergeTaskOutputFlow', () => {\n [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1 })],\n makeFieldsetBindingClient({ apiNameBinding: 'fs-new', order: 0, sharedFieldsetId: 99 }),\n );\n- const rows = assertRowsDefined(result);\n- const lastRow = rows[rows.length - 1];\n+ const lastRow = result[result.length - 1];\n expect(lastRow.kind).toBe('fieldset');\n expect(lastRow.kind === 'fieldset' && lastRow.apiNameBinding).toBe('fs-new');\n });\n });\n \n describe('buildRowsWithRemovedFieldset', () => {\n- it('removes fieldset by sharedFieldsetId, other rows are preserved', () => {\n+ it('removes fieldset by apiNameBinding, other rows are preserved', () => {\n const rows = buildRowsWithRemovedFieldset(\n [field('a', 0)],\n [\n- makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1 }),\n+ makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1, sharedFieldsetId: 1 }),\n makeFieldsetBindingClient({ apiNameBinding: 'fs-2', order: 2, sharedFieldsetId: 2 }),\n ],\n- 1,\n+ 'fs-1',\n );\n const apiNames = rows.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n expect(apiNames).not.toContain('fs-1');\n expect(apiNames).toContain('fs-2');\n expect(apiNames).toContain('a');\n });\n \n+ it('removes only the targeted duplicate instance by apiNameBinding leaving other instances intact', () => {\n+ const rows = buildRowsWithRemovedFieldset(\n+ [field('a', 0)],\n+ [\n+ makeFieldsetBindingClient({ apiNameBinding: 'fs-1-instance-1', order: 1, sharedFieldsetId: 10 }),\n+ makeFieldsetBindingClient({ apiNameBinding: 'fs-1-instance-2', order: 2, sharedFieldsetId: 10 }),\n+ ],\n+ 'fs-1-instance-1',\n+ );\n+ const apiNames = rows.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n+ expect(apiNames).not.toContain('fs-1-instance-1');\n+ expect(apiNames).toContain('fs-1-instance-2');\n+ });\n+\n it('does not throw when fieldset is absent — returns rows unchanged', () => {\n const rows = buildRowsWithRemovedFieldset(\n [field('a', 0)],\n [makeFieldsetBindingClient({ apiNameBinding: 'fs-1', order: 1 })],\n- 999,\n+ 'non-existent-binding',\n );\n const apiNames = rows.map((row) => (row.kind === 'field' ? row.field.apiName : row.apiNameBinding));\n expect(apiNames).toContain('fs-1');", "status": "modified"}, {"additions": 3, "deletions": 6, "filename": "frontend/src/public/components/TemplateEdit/TaskOutputFlow/mergeTaskOutputFlow.ts", "patch": "@@ -117,20 +117,17 @@ export function buildRowsWithAddedFieldset(\n fields: IExtraField[],\n fieldsets: IFieldsetBindingClient[],\n newFieldsetBinding: IFieldsetBindingClient,\n-): TMergedTaskOutputRow[] | null {\n- if (fieldsets.some((fieldset) => fieldset.sharedFieldsetId === newFieldsetBinding.sharedFieldsetId)) {\n- return null;\n- }\n+): TMergedTaskOutputRow[] {\n const nextFieldsets = [...fieldsets, newFieldsetBinding];\n return buildMergedTaskOutputRows(fields, nextFieldsets);\n }\n \n export function buildRowsWithRemovedFieldset(\n fields: IExtraField[],\n fieldsets: IFieldsetBindingClient[],\n- sharedFieldsetId: number,\n+ apiNameBinding: string,\n ): TMergedTaskOutputRow[] {\n- const nextFieldsets = fieldsets.filter((fieldset) => fieldset.sharedFieldsetId !== sharedFieldsetId);\n+ const nextFieldsets = fieldsets.filter((fieldset) => fieldset.apiNameBinding !== apiNameBinding);\n return buildMergedTaskOutputRows(fields, nextFieldsets);\n }\n ", "status": "modified"}], "message": "Merge branch 'master' of github.com:pneumaticapp/pneumaticworkflow into frontend/fieldsets/48741__provide_information_regarding_the_binding_of_the_field_set_to_specific_templates", "sha": "fd419fbd669e3223b20b5a81917eab66870449fc"}, {"author": "Maria-Lordwill", "date": "2026-08-13T06:00:33Z", "files": [{"additions": 0, "deletions": 19, "filename": "frontend/src/public/assets/css/mixins/fieldsets.pcss", "patch": "@@ -1,19 +0,0 @@\n-@define-mixin fieldset-field-readonly {\n- cursor: default;\n- color: var(--pneumatic-color-black72);\n- background-color: var(--pneumatic-color-black4);\n- border: 0.1rem solid transparent;\n- opacity: 1;\n-}\n-\n-@define-mixin fieldset-textarea-readonly {\n- @mixin fieldset-field-readonly;\n- resize: none;\n-}\n-\n-@define-mixin fieldset-option-readonly {\n- field-sizing: content;\n- width: auto;\n- padding: 0.4rem 1.2rem;\n- border-radius: 0.6rem;\n-}", "status": "removed"}, {"additions": 34, "deletions": 7, "filename": "frontend/src/public/components/Fieldsets/FieldsetDetails/FieldsetDetails.css", "patch": "@@ -88,7 +88,12 @@\n }\n \n &:disabled {\n- @mixin fieldset-textarea-readonly;\n+ cursor: default;\n+ color: var(--pneumatic-color-black72);\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid transparent;\n+ opacity: 1;\n+ resize: none;\n }\n }\n \n@@ -111,7 +116,11 @@\n }\n \n &:disabled {\n- @mixin fieldset-field-readonly;\n+ cursor: default;\n+ color: var(--pneumatic-color-black72);\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid transparent;\n+ opacity: 1;\n }\n }\n \n@@ -143,7 +152,11 @@\n }\n \n &:disabled {\n- @mixin fieldset-field-readonly;\n+ cursor: default;\n+ color: var(--pneumatic-color-black72);\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid transparent;\n+ opacity: 1;\n }\n }\n \n@@ -203,13 +216,19 @@\n }\n \n [class*=\"kickoff-create-field-option__input\"]:disabled {\n- @mixin fieldset-option-readonly;\n+ field-sizing: content;\n+ width: auto;\n+ padding: 0.4rem 1.2rem;\n+ border-radius: 0.6rem;\n max-width: 100%;\n }\n \n [class*=\"labeled-checkbox__input\"]:disabled,\n [class*=\"labeled-radiobutton__input\"]:disabled {\n- @mixin fieldset-option-readonly;\n+ field-sizing: content;\n+ width: auto;\n+ padding: 0.4rem 1.2rem;\n+ border-radius: 0.6rem;\n max-width: calc(100% - 3.2rem);\n }\n \n@@ -359,7 +378,11 @@\n }\n \n &:disabled {\n- @mixin fieldset-field-readonly;\n+ cursor: default;\n+ color: var(--pneumatic-color-black72);\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid transparent;\n+ opacity: 1;\n }\n }\n \n@@ -380,7 +403,11 @@\n }\n \n &:disabled {\n- @mixin fieldset-field-readonly;\n+ cursor: default;\n+ color: var(--pneumatic-color-black72);\n+ background-color: var(--pneumatic-color-black4);\n+ border: 0.1rem solid transparent;\n+ opacity: 1;\n opacity: 0.55;\n }\n }", "status": "modified"}], "message": "48741 refactor(fieldsets): inline fieldset readonly mixins and remove fieldsets.pcss", "sha": "2f6a55f51f5e8372ff695382c176b78198b4e49d"}], "post_review_commits": ["3d365f7276b8e0d687e26d1c1ae823e5d4c3b60a", "2f068893ae5d30561392b2c879eef3826c72b3db", "86834a5cc6c1d783e0d8cc8e99adc862eb11aeee", "d718aaeeffc1db92aba0d3562c324e15afff6273", "74c69560b445dbbb5c52bed9e0ee9863490f78fd", "8a986cd475b7dd595627d2783f5c3f0cac93815a", "b8079bf0b7d21c56c8192ee9cfab0adb1b647422", "5b83e093ef6e83634157da720b18de8735f9d5bf", "87ef3f9a8c5ae989bfe20acbb33b9a7d471994aa", "26132d2a7e93ca1e38b9e51b89fb22ce27f59825", "1dc8be2190c26123381a4c2271646e8b7564963f", "524ceb4fd8c5f441c754e2e3f4c46d9ee28eecce", "ef8e17e97a658b507ac39ef283f8ae4d9fde3f39", "33c1ad8d6a01706cf99aaddcc39c6774f158ac69", "ec1092cddf8f8aaad43a5725b40fd355a2ab2b58", "a0784ae0cd6660f3c102dd8975d3857ca339998c", "8f0b855888a3671819eec85a1865acf9d03af6bf", "8ce2ad4853bac9179543299bdba5b820b1eeadb6", "335e2cb8cffa362654bbdfaf98f03d170922a402", "aaa19461bc18da7d53622e744a132c09775eccf5", "c99f6008cbddeb6e201210ac71ce10659232f0a4", "fc498dab04ea07539b3a79f179403680275fd942", "624e5dd12d93d44eafc1e489ff9385d38c5c87a6"], "pr_author": "Maria-Lordwill", "pr_title": "48741 frontend [ fieldsets ] provide information regarding the binding of the field set to specific templates", "repo_name": "pneumaticapp/pneumaticworkflow"}, "repo": "pneumaticapp/pneumaticworkflow", "snapshot": "snapshots/0ac4c0843fa48eb4146c1fe584b4657194b65c1eb5d3b3aeeeae27e91bef3b68.pack", "split": "eval", "task_id": "f88c2b087910121bdeb05f673f2fd83beec970a909fc01611033c22c76a04380"} {"base_sha": "c8023b8490c9d3bfc3a8ba266381808458e7d162", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/gnanam1990/webmcp-loom/pull/9", "id": "f9be7fc05313be72a84aebf74a232900f3b0e8b69b569253924e243c4cf70a89", "preparation_mode": "source-only", "snapshot": {"base_ref": "c8023b8490c9d3bfc3a8ba266381808458e7d162", "base_sha": "c8023b8490c9d3bfc3a8ba266381808458e7d162", "body": "", "head_ref": "04577dce833419b9e9174864e9ffe7cf636693f9", "head_sha": "04577dce833419b9e9174864e9ffe7cf636693f9", "name": "webmcp-loom", "number": 9, "owner": "gnanam1990", "pr_url": "https://github.com/gnanam1990/webmcp-loom/pull/9", "title": ""}}, "head_sha": "04577dce833419b9e9174864e9ffe7cf636693f9", "metadata": {"group_id": "041d12a854036de96f76c0207cdc73d77ccbf698ae4709f1b25935f313b38f78", "snapshot": {"base_sha": "c8023b8490c9d3bfc3a8ba266381808458e7d162", "external_requirements": [], "head_sha": "04577dce833419b9e9174864e9ffe7cf636693f9", "objects": 99, "objects_sha256": "604058ead215335c1b1b3a613f7dd0f522406c70063d087b204a3baaaec4868a", "patch_sha256": "f4617e73bc550b1104c6505450bfd545ba47f15c6c925cd5bf43d9fbddc7bdb0"}}, "pr_number": 9, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "eb03c3710a93", "description": "The pagehide handler disposed WebMCP tools even when the page entered the back-forward cache, leaving a restored page without registrations.", "file_path": "apps/travel-showcase/src/app/webmcp-registration.ts"}, {"action_id": "A2", "action_type": "improvement", "category": "other", "commit_sha": "eb03c3710a93", "description": "When WebMCP was unavailable, registration resolved to null silently, so developers could miss that travel tools had not been published.", "file_path": "apps/travel-showcase/src/app/webmcp-registration.ts"}, {"action_id": "A3", "action_type": "fix", "category": "bug", "commit_sha": "eb03c3710a93", "description": "An in-app tool write notified session subscribers before its terminal runtime event updated the trace, exposing a committed itinerary revision while the write still appeared unfinished and causing a second notification.", "file_path": "apps/travel-showcase/src/app/session.ts"}, {"action_id": "A4", "action_type": "fix", "category": "bug", "commit_sha": "eb03c3710a93", "description": "The root typecheck used emitting project references, so checking types could create build outputs and depend on generated runtime declarations instead of checking workspace source without emitting.", "file_path": "package.json"}, {"action_id": "A5", "action_type": "fix", "category": "bug", "commit_sha": "bff43704d4f9", "description": "The regression test rejected only a committed write whose trace was still `running`; it could pass if the trace was in another non-succeeded state, such as `awaiting_approval`.", "file_path": "apps/travel-showcase/src/app/session.test.ts"}, {"action_id": "A6", "action_type": "improvement", "category": "refactor", "commit_sha": "bff43704d4f9", "description": "TypeScript and Vite maintained separate hard-coded aliases for the runtime source, allowing typechecking and bundling to resolve different implementations if either mapping changed.", "file_path": "apps/travel-showcase/vite.config.ts"}, {"action_id": "A7", "action_type": "fix", "category": "bug", "commit_sha": "34ca7d9613f3", "description": "The workspace-only root typecheck would silently omit `benchmarks/`, which is not a workspace, leaving benchmark type errors undetected.", "file_path": "package.json"}, {"action_id": "A8", "action_type": "new_feature", "category": "other", "commit_sha": "34ca7d9613f3", "description": "The application could not move an itinerary item from the board, despite the store supporting moves; users had no direct way to change an item's date.", "file_path": "apps/travel-showcase/src/app/App.tsx"}, {"action_id": "A9", "action_type": "fix", "category": "bug", "commit_sha": "34ca7d9613f3", "description": "Board removal was disabled while the agent ran, preventing a person from making a concurrent edit through the UI even though the session supports stale-state detection.", "file_path": "apps/travel-showcase/src/app/App.tsx"}, {"action_id": "A10", "action_type": "fix", "category": "bug", "commit_sha": "34ca7d9613f3", "description": "The budget meter's accessible label reported only a capped percentage, concealing the actual committed amount and over-budget amount from screen-reader users.", "file_path": "apps/travel-showcase/src/app/App.tsx"}, {"action_id": "A11", "action_type": "fix", "category": "bug", "commit_sha": "34ca7d9613f3", "description": "After an approval was denied, the session briefly published `running` again before reaching `denied`, producing a misleading status announcement.", "file_path": "apps/travel-showcase/src/app/session.ts"}, {"action_id": "A12", "action_type": "fix", "category": "bug", "commit_sha": "34ca7d9613f3", "description": "The merged input helper imported `JsonObject` from `runtime-contract.js`, a file removed by this branch, so the application could not compile.", "file_path": "apps/travel-showcase/src/input.ts"}], "commits_under_review": [{"author": "gnanam1990", "date": "2026-08-29T07:21:38Z", "files": [{"additions": 3, "deletions": 1, "filename": "README.md", "patch": "@@ -6,7 +6,9 @@ WebMCP made websites usable by agents. WebMCP Loom makes them agent-native for p\n \n ## Status\n \n-The team foundation is merged. The runtime track now contains the first independently implemented TypeScript foundation: bounded multi-step execution, deterministic validation, approval and stale-state boundaries, cancellation, a model-neutral contract, WebMCP adapters, tests and built-package smoke fixtures.\n+The runtime and collaborative travel foundations are merged: bounded multi-step execution, deterministic validation, approval and stale-state boundaries, cancellation, a model-neutral contract, WebMCP adapters, a shared-state Japan planner, visible approvals, responsive UI, tests and built-package smoke fixtures.\n+\n+The travel application now creates one canonical tool array for both its in-app runtime and document WebMCP registration. External WebMCP writes update the same subscribed store the visible board reads, so the two entry points cannot drift onto separate state.\n \n The earlier [Latchwork runtime foundation](https://github.com/gnanam1990/latchwork/pull/7) remains source evidence; WebMCP Loom's implementation is independently structured and revalidated here.\n ", "status": "modified"}, {"additions": 13, "deletions": 9, "filename": "apps/travel-showcase/README.md", "patch": "@@ -1,8 +1,6 @@\n # `@webmcp-loom/travel-showcase`\n \n-The deterministic Japan travel domain, its shared state, and the canonical WebMCP tool surface for the collaborative showcase.\n-\n-This package is the domain foundation only. There is no user interface yet — the interface is specified in [the collaboration contract](docs/collaboration-contract.md) and built in the Day 3 and Day 5 tracks.\n+The deterministic Japan travel domain, collaborative application, shared state, and canonical WebMCP tool surface for the showcase.\n \n ## What is implemented\n \n@@ -11,7 +9,9 @@ This package is the domain foundation only. There is no user interface yet — t\n - a shared store whose revision increments on every accepted write;\n - compare-and-swap on agent writes, and revision-free human edits that preserve canonical domain invariants;\n - ten tool definitions with schemas, read/write annotations and deterministic executors;\n-- 65 domain tests.\n+- a responsive itinerary, budget, trace and visible-approval interface;\n+- one application factory that hands the same store and tool array to the in-app runtime and document WebMCP registration;\n+- deterministic domain, collaboration, accessibility-helper and WebMCP integration tests.\n \n ## Shared state and revisions\n \n@@ -37,6 +37,14 @@ Read tools return the current `revision` alongside their data, and write tools r\n \n When the in-app runtime also supplies its captured revision, the executor requires the two to agree.\n \n+The store publishes accepted commits to subscribers. That notification is what lets an external WebMCP write invalidate the session snapshot and immediately update the visible itinerary and budget. Rejected writes do not emit.\n+\n+## WebMCP registration\n+\n+The browser entry point calls `installDocumentRuntimeTools()` with the exact tool array used by the in-app session. In browsers that expose `document.modelContext`, all ten tools are registered and share the visible application state. Unsupported browsers keep the in-app experience working and return `null` from the registration adapter.\n+\n+Registration is cancellation-bound to the page lifecycle. A deterministic integration test supplies a draft-compatible `document.modelContext`, verifies all ten registrations, executes an external write, and proves the session snapshot advances to the same revision.\n+\n ## Tool surface\n \n Seven read tools, three write tools.\n@@ -64,11 +72,7 @@ There is no booking, payment, credential, account or deletion capability, and no\n \n ## Runtime types\n \n-`src/runtime-contract.ts` mirrors the runtime's tool contract structurally rather than importing `@webmcp-loom/runtime`.\n-\n-That package typechecks with `noEmit`, so it publishes no declarations until its build step, and `npm run verify` typechecks before it builds — importing it here would make a clean checkout fail on ordering alone. The mirrored types are structural, so the tool array is assignable to `RuntimeTool[]` without a cast.\n-\n-Day 3 integration owns replacing this with the real import and adding a compile-time conformance assertion. Until then, keep `src/runtime-contract.ts` in sync with `packages/runtime/src/types.ts`.\n+The package imports `RuntimeTool`, executor context and JSON types directly from `@webmcp-loom/runtime`; there is no ambient or structural mirror to drift. TypeScript project references build the runtime declarations before checking or building the application, including from a clean checkout. Tool schemas are validated by the runtime's real `assertValidToolSchema()` implementation in the travel test suite.\n \n ## Verification\n ", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "apps/travel-showcase/package.json", "patch": "@@ -15,7 +15,7 @@\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"scripts\": {\n- \"build\": \"tsc -p tsconfig.build.json && vite build\",\n+ \"build\": \"tsc -b tsconfig.build.json && vite build\",\n \"dev\": \"vite\",\n \"preview\": \"vite preview\"\n },", "status": "modified"}, {"additions": 3, "deletions": 5, "filename": "apps/travel-showcase/src/app/App.tsx", "patch": "@@ -1,7 +1,6 @@\n-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\n+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\n import { ACTIVITIES, FLIGHTS, STAYS } from '../inventory.js';\n-import { createSession } from './session.js';\n-import type { SessionSnapshot, TraceLine } from './session.js';\n+import type { Session, SessionSnapshot, TraceLine } from './session.js';\n import type { ItineraryItem, TripState } from '../types.js';\n \n const INR = new Intl.NumberFormat('en-IN', { maximumFractionDigits: 0 });\n@@ -20,8 +19,7 @@ const REPAIR_GOAL = 'Rework everything around that and keep the same budget.';\n \n const BUSY: readonly SessionSnapshot['status'][] = ['running', 'awaiting_approval'];\n \n-export function App(): React.JSX.Element {\n- const session = useMemo(() => createSession(), []);\n+export function App({ session }: { session: Session }): React.JSX.Element {\n const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot);\n const [goal, setGoal] = useState(HERO_GOAL);\n const runButton = useRef(null);", "status": "modified"}, {"additions": 134, "deletions": 0, "filename": "apps/travel-showcase/src/app/application.test.ts", "patch": "@@ -0,0 +1,134 @@\n+import { afterEach, describe, expect, it, vi } from 'vitest';\n+import { installDocumentRuntimeTools } from '@webmcp-loom/runtime';\n+import { createTravelApplication } from './application.js';\n+import type {\n+ JsonObject,\n+ RegisteredWebMcpTool,\n+ WebMcpModelContext,\n+ WebMcpToolDefinition,\n+} from '@webmcp-loom/runtime';\n+\n+interface FakeWebMcp {\n+ readonly context: WebMcpModelContext;\n+ readonly definitions: Map;\n+ readonly registrationSignals: AbortSignal[];\n+}\n+\n+function createFakeWebMcp(): FakeWebMcp {\n+ const definitions = new Map();\n+ const registrationSignals: AbortSignal[] = [];\n+ const registeredTools = (): RegisteredWebMcpTool[] => [...definitions.values()].map((tool) => ({\n+ name: tool.name,\n+ description: tool.description,\n+ ...(tool.title === undefined ? {} : { title: tool.title }),\n+ ...(tool.inputSchema === undefined ? {} : { inputSchema: tool.inputSchema }),\n+ ...(tool.annotations === undefined ? {} : { annotations: tool.annotations }),\n+ }));\n+\n+ const context: WebMcpModelContext = {\n+ registerTool: (tool, options) => {\n+ definitions.set(tool.name, tool);\n+ if (options?.signal !== undefined) registrationSignals.push(options.signal);\n+ return Promise.resolve();\n+ },\n+ getTools: () => Promise.resolve(registeredTools()),\n+ executeTool: async (tool, input: JsonObject = {}, options = {}) => {\n+ const definition = definitions.get(tool.name);\n+ if (definition === undefined) throw new Error(`Tool is not registered: ${tool.name}`);\n+ const output = await definition.execute(input, { signal: options.signal });\n+ return JSON.stringify(output) ?? 'null';\n+ },\n+ };\n+\n+ return { context, definitions, registrationSignals };\n+}\n+\n+afterEach(() => vi.unstubAllGlobals());\n+\n+describe('travel application WebMCP integration', () => {\n+ it('registers the canonical tools and reflects an external write in the UI session', async () => {\n+ const webmcp = createFakeWebMcp();\n+ vi.stubGlobal('document', { modelContext: webmcp.context });\n+ const application = createTravelApplication();\n+ let notifications = 0;\n+ application.session.subscribe(() => { notifications += 1; });\n+\n+ const registration = await installDocumentRuntimeTools(application.tools);\n+ expect(registration).not.toBeNull();\n+ expect([...webmcp.definitions.keys()].sort()).toEqual([\n+ 'add_itinerary_item',\n+ 'get_budget_summary',\n+ 'get_itinerary',\n+ 'get_trip_constraints',\n+ 'list_destinations',\n+ 'move_itinerary_item',\n+ 'remove_itinerary_item',\n+ 'search_activities',\n+ 'search_flights',\n+ 'search_stays',\n+ ]);\n+\n+ const addTool = (await webmcp.context.getTools()).find(\n+ (tool) => tool.name === 'add_itinerary_item',\n+ );\n+ if (addTool === undefined) throw new Error('Expected the add tool to be registered.');\n+ const result = JSON.parse(await webmcp.context.executeTool(addTool, {\n+ expectedRevision: 1,\n+ kind: 'activity',\n+ refId: 'ac-tok-teamlab',\n+ date: '2026-11-06',\n+ })) as { revision: number };\n+\n+ expect(result.revision).toBe(2);\n+ expect(application.session.getSnapshot().trip).toMatchObject({\n+ revision: 2,\n+ items: [{ activityId: 'ac-tok-teamlab', kind: 'activity' }],\n+ });\n+ expect(notifications).toBe(1);\n+\n+ registration?.dispose();\n+ expect(webmcp.registrationSignals).toHaveLength(10);\n+ expect(webmcp.registrationSignals.every((signal) => signal.aborted)).toBe(true);\n+ });\n+\n+ it('rejects a pending in-app write after an external WebMCP write advances the revision', async () => {\n+ const webmcp = createFakeWebMcp();\n+ vi.stubGlobal('document', { modelContext: webmcp.context });\n+ const application = createTravelApplication();\n+ await installDocumentRuntimeTools(application.tools);\n+\n+ let resolveAwaiting: (() => void) | undefined;\n+ const awaitingApproval = new Promise((resolve) => { resolveAwaiting = resolve; });\n+ application.session.subscribe(() => {\n+ if (application.session.getSnapshot().status === 'awaiting_approval') {\n+ resolveAwaiting?.();\n+ resolveAwaiting = undefined;\n+ }\n+ });\n+\n+ const run = application.session.run('Prepare the trip.');\n+ await awaitingApproval;\n+ const addTool = (await webmcp.context.getTools()).find(\n+ (tool) => tool.name === 'add_itinerary_item',\n+ );\n+ if (addTool === undefined) throw new Error('Expected the add tool to be registered.');\n+ await webmcp.context.executeTool(addTool, {\n+ expectedRevision: 1,\n+ kind: 'activity',\n+ refId: 'ac-tok-teamlab',\n+ date: '2026-11-06',\n+ });\n+\n+ expect(application.session.getSnapshot().trip.revision).toBe(2);\n+ application.session.approve();\n+ await run;\n+\n+ expect(application.session.getSnapshot()).toMatchObject({\n+ status: 'stale',\n+ trip: {\n+ revision: 2,\n+ items: [{ activityId: 'ac-tok-teamlab', kind: 'activity' }],\n+ },\n+ });\n+ });\n+});", "status": "added"}, {"additions": 26, "deletions": 0, "filename": "apps/travel-showcase/src/app/application.ts", "patch": "@@ -0,0 +1,26 @@\n+import { createTripStore } from '../state.js';\n+import { createTravelTools } from '../tools.js';\n+import { createSession } from './session.js';\n+import type { RuntimeTool } from '@webmcp-loom/runtime';\n+import type { TripStore } from '../state.js';\n+import type { Session } from './session.js';\n+\n+export interface TravelApplication {\n+ readonly session: Session;\n+ readonly store: TripStore;\n+ readonly tools: readonly RuntimeTool[];\n+}\n+\n+/**\n+ * Creates one store and one canonical tool array for both the in-app runtime\n+ * and document WebMCP registration. Keeping this wiring in one factory makes\n+ * it impossible for the two agent entry points to drift onto separate state.\n+ */\n+export function createTravelApplication(store: TripStore = createTripStore()): TravelApplication {\n+ const tools = Object.freeze(createTravelTools(store));\n+ return Object.freeze({\n+ store,\n+ tools,\n+ session: createSession(store, tools),\n+ });\n+}", "status": "added"}, {"additions": 22, "deletions": 1, "filename": "apps/travel-showcase/src/app/main.tsx", "patch": "@@ -1,13 +1,34 @@\n import { StrictMode } from 'react';\n import { createRoot } from 'react-dom/client';\n+import { installDocumentRuntimeTools } from '@webmcp-loom/runtime';\n import { App } from './App.js';\n+import { createTravelApplication } from './application.js';\n import './styles.css';\n \n const mount = document.querySelector('#root');\n if (mount === null) throw new Error('Missing #root mount point.');\n+const application = createTravelApplication();\n \n createRoot(mount).render(\n \n- \n+ \n ,\n );\n+\n+const registrationController = new AbortController();\n+const registration = installDocumentRuntimeTools(application.tools, {\n+ signal: registrationController.signal,\n+});\n+void registration.catch((error: unknown) => {\n+ if (!registrationController.signal.aborted) {\n+ console.error('WebMCP travel-tool registration failed.', error);\n+ }\n+});\n+\n+const disposeRegistration = (): void => {\n+ window.removeEventListener('pagehide', disposeRegistration);\n+ registrationController.abort();\n+ void registration.then((installed) => installed?.dispose(), () => undefined);\n+};\n+window.addEventListener('pagehide', disposeRegistration, { once: true });\n+if (import.meta.hot !== undefined) import.meta.hot.dispose(disposeRegistration);", "status": "modified"}, {"additions": 3, "deletions": 1, "filename": "apps/travel-showcase/src/app/session.test.ts", "patch": "@@ -146,9 +146,11 @@ describe('human edits and stale state', () => {\n it('stops rather than overwriting when the person edits mid-run', async () => {\n const store = createTripStore();\n const session = createSession(store);\n+ let edited = false;\n // Edit the shared state at the moment the agent asks to write.\n session.subscribe(() => {\n- if (session.getSnapshot().status === 'awaiting_approval') {\n+ if (session.getSnapshot().status === 'awaiting_approval' && !edited) {\n+ edited = true;\n store.editAsHuman((items) => items);\n session.approve();\n }", "status": "modified"}, {"additions": 11, "deletions": 4, "filename": "apps/travel-showcase/src/app/session.ts", "patch": "@@ -16,7 +16,12 @@ import { ACTIVITIES, DESTINATIONS, FLIGHTS, STAYS } from '../inventory.js';\n import { createTripStore } from '../state.js';\n import { createTravelTools } from '../tools.js';\n import { HERO_SCRIPT, REPAIR_SCRIPT, createScriptedModel } from './scripted-model.js';\n-import type { AgentApprovalRequest, AgentEvent, JsonObject } from '@webmcp-loom/runtime';\n+import type {\n+ AgentApprovalRequest,\n+ AgentEvent,\n+ JsonObject,\n+ RuntimeTool,\n+} from '@webmcp-loom/runtime';\n import type { TripStore } from '../state.js';\n import type { BudgetSummary, ItineraryItem, TripState } from '../types.js';\n \n@@ -164,8 +169,10 @@ function scriptFor(trip: TripState): readonly typeof HERO_SCRIPT[number][] {\n return trip.items.length === 0 ? HERO_SCRIPT : REPAIR_SCRIPT;\n }\n \n-export function createSession(store: TripStore = createTripStore()): Session {\n- const tools = createTravelTools(store);\n+export function createSession(\n+ store: TripStore = createTripStore(),\n+ tools: readonly RuntimeTool[] = createTravelTools(store),\n+): Session {\n const listeners = new Set<() => void>();\n \n let status: SessionStatus = 'idle';\n@@ -186,6 +193,7 @@ export function createSession(store: TripStore = createTripStore()): Session {\n cached = null;\n for (const listener of listeners) listener();\n };\n+ store.subscribe(emit);\n \n const setLineState = (step: number, state: TraceLineState, detail?: string): void => {\n trace = trace.map((line) => (\n@@ -341,7 +349,6 @@ export function createSession(store: TripStore = createTripStore()): Session {\n \n removeItem: (itemId: string) => {\n store.editAsHuman((items) => items.filter((item) => item.id !== itemId));\n- emit();\n },\n \n reset: () => {", "status": "modified"}, {"additions": 0, "deletions": 46, "filename": "apps/travel-showcase/src/runtime-contract.ts", "patch": "@@ -1,46 +0,0 @@\n-/**\n- * Structural mirror of the runtime's tool contract.\n- *\n- * The travel domain deliberately does not import `@webmcp-loom/runtime` yet.\n- * That package typechecks with `noEmit`, so it publishes no declarations before\n- * its build step, and `npm run verify` typechecks before it builds. Importing it\n- * here would make a clean checkout fail on ordering alone.\n- *\n- * These declarations are structural, so a tool array built against them is\n- * assignable to `RuntimeTool[]` without a cast. Day 3 integration owns wiring\n- * the two together and should add a compile-time conformance assertion against\n- * the real exported types at that point, which is also what will catch drift if\n- * the runtime contract changes.\n- *\n- * Keep in sync with `packages/runtime/src/types.ts`.\n- */\n-\n-export type JsonPrimitive = boolean | null | number | string;\n-export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n-export type JsonObject = { [key: string]: JsonValue };\n-export type JsonSchema = Record;\n-\n-export type RuntimeStateRevision = number | string;\n-\n-export interface RuntimeToolAnnotations {\n- readOnlyHint: boolean;\n- untrustedContentHint?: boolean;\n-}\n-\n-export interface RuntimeToolExecuteContext {\n- signal: AbortSignal | undefined;\n- expectedStateRevision: RuntimeStateRevision | undefined;\n-}\n-\n-export interface RuntimeTool {\n- name: string;\n- title: string;\n- description: string;\n- inputSchema: JsonSchema;\n- annotations: RuntimeToolAnnotations;\n- origin?: string;\n- execute(input: JsonObject, context: RuntimeToolExecuteContext): unknown | Promise;\n-}\n-\n-/** A tool as the runtime describes it to an approval surface: metadata without the executor. */\n-export type RuntimeToolDescriptor = Omit;", "status": "removed"}, {"additions": 0, "deletions": 120, "filename": "apps/travel-showcase/src/runtime-module.d.ts", "patch": "@@ -1,120 +0,0 @@\n-/**\n- * Ambient declaration for the runtime package.\n- *\n- * The UI needs the runtime's *values* (`runAgentRuntime`,\n- * `createStaticToolProvider`), not just its types, so the structural mirror in\n- * `runtime-contract.ts` is not enough on its own. The runtime package\n- * typechecks with `noEmit` and publishes no declarations until its build step,\n- * while `npm run verify` typechecks before it builds, so a plain import cannot\n- * resolve types on a clean checkout.\n- *\n- * Declaring the module here lets TypeScript resolve the imports while Vite and\n- * Node resolve the real `dist/index.js` at build and run time. The shapes below\n- * are the subset of the public API this application uses.\n- *\n- * Keep in sync with `packages/runtime/src/types.ts`. Day 3 integration should\n- * replace both this file and `runtime-contract.ts` with the real import once the\n- * runtime emits declarations.\n- */\n-\n-declare module '@webmcp-loom/runtime' {\n- import type {\n- JsonObject,\n- JsonSchema,\n- RuntimeStateRevision,\n- RuntimeTool,\n- RuntimeToolDescriptor,\n- } from './runtime-contract.js';\n-\n- export type { JsonObject, JsonSchema, RuntimeStateRevision, RuntimeTool };\n-\n- export interface RuntimeModelRequest {\n- prompt: string;\n- responseSchema: JsonSchema;\n- signal: AbortSignal | undefined;\n- }\n-\n- export interface RuntimeModel {\n- generate(request: RuntimeModelRequest): Promise;\n- }\n-\n- export interface RuntimeToolProvider {\n- getTools(context: { signal: AbortSignal | undefined }):\n- | Promise\n- | readonly RuntimeTool[];\n- }\n-\n- export interface AgentToolResult {\n- step: number;\n- tool: string;\n- input: JsonObject;\n- ok: boolean;\n- output?: unknown;\n- error?: string;\n- }\n-\n- export interface AgentApprovalRequest {\n- step: number;\n- tool: RuntimeToolDescriptor;\n- input: JsonObject;\n- stateRevision?: RuntimeStateRevision;\n- }\n-\n- export type ToolRefreshPhase = 'pre_execute' | 'prompt';\n-\n- export type AgentEvent =\n- | { type: 'approval_required'; step: number; toolName: string }\n- | { type: 'cancelled'; step: number }\n- | { type: 'completed'; step: number; message: string }\n- | { type: 'denied'; step: number; toolName: string }\n- | {\n- type: 'stale_state';\n- step: number;\n- expected: RuntimeStateRevision;\n- current: RuntimeStateRevision;\n- }\n- | { type: 'step_limit_reached'; step: number }\n- | { type: 'tool_call_validated'; step: number; toolName: string; input: JsonObject }\n- | { type: 'tool_failed'; step: number; toolName: string; error: string }\n- | { type: 'tool_started'; step: number; toolName: string }\n- | { type: 'tool_succeeded'; step: number; toolName: string }\n- | {\n- type: 'tools_refreshed';\n- step: number;\n- phase: ToolRefreshPhase;\n- toolNames: string[];\n- };\n-\n- interface AgentRunResultBase {\n- events: AgentEvent[];\n- history: AgentToolResult[];\n- }\n-\n- export type AgentRunResult = AgentRunResultBase & (\n- | { status: 'approval_required'; pendingApproval: AgentApprovalRequest }\n- | { status: 'cancelled' }\n- | { status: 'completed'; message: string }\n- | { status: 'denied'; deniedCall: AgentApprovalRequest }\n- | {\n- status: 'stale_state';\n- expectedRevision: RuntimeStateRevision;\n- currentRevision: RuntimeStateRevision;\n- }\n- | { status: 'step_limit' }\n- | { status: 'write_failed'; failedCall: AgentApprovalRequest; error: string }\n- );\n-\n- export interface AgentRunOptions {\n- goal: string;\n- model: RuntimeModel;\n- toolProvider: RuntimeToolProvider;\n- approve?: (request: AgentApprovalRequest) => boolean | Promise;\n- getStateRevision?: () => Promise | RuntimeStateRevision;\n- maxSteps?: number;\n- onEvent?: (event: AgentEvent) => Promise | void;\n- signal?: AbortSignal;\n- }\n-\n- export function runAgentRuntime(options: AgentRunOptions): Promise;\n- export function createStaticToolProvider(tools: readonly RuntimeTool[]): RuntimeToolProvider;\n-}", "status": "removed"}, {"additions": 35, "deletions": 0, "filename": "apps/travel-showcase/src/state.test.ts", "patch": "@@ -10,6 +10,41 @@ function storeWithFlight(): { store: ReturnType; item: I\n }\n \n describe('trip store revision contract', () => {\n+ it('notifies subscribers only after accepted state commits', () => {\n+ const store = createTripStore();\n+ let notifications = 0;\n+ const unsubscribe = store.subscribe(() => { notifications += 1; });\n+\n+ store.addItem(1, {\n+ kind: 'activity',\n+ activityId: 'ac-tok-teamlab',\n+ date: '2026-11-06',\n+ });\n+ expect(notifications).toBe(1);\n+\n+ expect(() => store.removeItem(1, 'it-1')).toThrow(TravelDomainError);\n+ expect(notifications).toBe(1);\n+\n+ unsubscribe();\n+ store.removeItem(2, 'it-1');\n+ expect(notifications).toBe(1);\n+ });\n+\n+ it('does not turn a committed write into an apparent failure when an observer throws', () => {\n+ const store = createTripStore();\n+ let laterObserverCalls = 0;\n+ store.subscribe(() => { throw new Error('observer failed'); });\n+ store.subscribe(() => { laterObserverCalls += 1; });\n+\n+ expect(() => store.addItem(1, {\n+ kind: 'activity',\n+ activityId: 'ac-tok-teamlab',\n+ date: '2026-11-06',\n+ })).not.toThrow();\n+ expect(store.getState()).toMatchObject({ revision: 2, items: [{ id: 'it-1' }] });\n+ expect(laterObserverCalls).toBe(1);\n+ });\n+\n it('starts at revision 1 with an empty itinerary', () => {\n const state = createTripStore().getState();\n expect(state.revision).toBe(1);", "status": "modified"}, {"additions": 15, "deletions": 0, "filename": "apps/travel-showcase/src/state.ts", "patch": "@@ -47,6 +47,8 @@ export type AddItemRequest =\n export interface TripStore {\n getState(): TripState;\n getBudgetSummary(): BudgetSummary;\n+ /** Notify application consumers after an accepted human or agent write commits. */\n+ subscribe(listener: () => void): () => void;\n /** Agent write. `expectedRevision` must match current state exactly. */\n addItem(expectedRevision: number, request: AddItemRequest): ItineraryItem;\n removeItem(expectedRevision: number, itemId: string): ItineraryItem;\n@@ -127,6 +129,7 @@ export function createTripStore(\n });\n let revision = 1;\n let items: readonly ItineraryItem[] = Object.freeze([]);\n+ const listeners = new Set<() => void>();\n \n /**\n * Derived from the highest generated identifier rather than the item count,\n@@ -383,6 +386,13 @@ export function createTripStore(\n items = freezeItems(next);\n nextItemNumber = Math.max(nextItemNumber, highestGeneratedNumber(items) + 1);\n revision += 1;\n+ for (const listener of [...listeners]) {\n+ try {\n+ listener();\n+ } catch {\n+ // Observers cannot roll back a committed write or make it appear failed.\n+ }\n+ }\n };\n \n items = freezeItems(initialItems);\n@@ -391,6 +401,11 @@ export function createTripStore(\n return {\n getState: snapshot,\n \n+ subscribe: (listener) => {\n+ listeners.add(listener);\n+ return () => listeners.delete(listener);\n+ },\n+\n getBudgetSummary: () => {\n const byKind: Record = { activity: 0, flight: 0, stay: 0 };\n let committedInr = 0;", "status": "modified"}, {"additions": 7, "deletions": 32, "filename": "apps/travel-showcase/src/tools.test.ts", "patch": "@@ -1,23 +1,14 @@\n import { describe, expect, it } from 'vitest';\n+import { assertValidToolSchema } from '@webmcp-loom/runtime';\n import { TravelDomainError, createTripStore } from './state.js';\n import { createTravelTools } from './tools.js';\n-import type { JsonObject, RuntimeTool, RuntimeToolExecuteContext } from './runtime-contract.js';\n+import type {\n+ JsonObject,\n+ RuntimeTool,\n+ RuntimeToolExecuteContext,\n+} from '@webmcp-loom/runtime';\n import type { TripStore } from './state.js';\n \n-/**\n- * Mirrors the runtime's bounded JSON Schema subset. The travel package cannot\n- * import the runtime validator before that package is built, so this guards\n- * against a schema keyword the runtime would reject at registration time.\n- * Day 3 integration replaces this with the real `assertValidToolSchema`.\n- */\n-const SUPPORTED_SCHEMA_KEYS = new Set([\n- '$id', '$schema', 'additionalProperties', 'const', 'default', 'deprecated',\n- 'description', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum',\n- 'items', 'maxItems', 'maxLength', 'maximum', 'minItems', 'minLength',\n- 'minimum', 'properties', 'readOnly', 'required', 'title', 'type',\n- 'writeOnly',\n-]);\n-\n const FORBIDDEN_CAPABILITY = /\\b(book|booking|pay|payment|purchase|checkout|credential|password|delete account|refund)\\b/i;\n \n function context(expectedStateRevision?: number): RuntimeToolExecuteContext {\n@@ -33,18 +24,6 @@ function call(tool: RuntimeTool | undefined, input: JsonObject, revision?: numbe\n return tool.execute(input, context(revision)) as JsonObject;\n }\n \n-function collectSchemaKeys(schema: unknown, found: Set): void {\n- if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) return;\n- for (const [key, value] of Object.entries(schema)) {\n- found.add(key);\n- if (key === 'properties' && typeof value === 'object' && value !== null) {\n- for (const child of Object.values(value)) collectSchemaKeys(child, found);\n- } else if (key === 'items') {\n- collectSchemaKeys(value, found);\n- }\n- }\n-}\n-\n describe('travel tool surface', () => {\n it('exposes 10 uniquely named tools inside the 8-12 planned range', () => {\n const tools = createTravelTools(createTripStore());\n@@ -81,11 +60,7 @@ describe('travel tool surface', () => {\n \n it('uses only JSON Schema keywords the runtime supports', () => {\n for (const tool of createTravelTools(createTripStore())) {\n- const found = new Set();\n- collectSchemaKeys(tool.inputSchema, found);\n- for (const key of found) {\n- expect(SUPPORTED_SCHEMA_KEYS.has(key), `${tool.name} uses ${key}`).toBe(true);\n- }\n+ expect(() => assertValidToolSchema(tool.inputSchema), tool.name).not.toThrow();\n expect(tool.inputSchema.type).toBe('object');\n expect(tool.inputSchema.additionalProperties).toBe(false);\n }", "status": "modified"}, {"additions": 5, "deletions": 1, "filename": "apps/travel-showcase/src/tools.ts", "patch": "@@ -16,7 +16,11 @@ import { ACTIVITIES, DESTINATIONS, FLIGHTS, STAYS } from './inventory.js';\n import { TravelDomainError } from './state.js';\n import type { AddItemRequest, TripStore } from './state.js';\n import type { ActivityTag, CityId } from './types.js';\n-import type { JsonObject, RuntimeTool, RuntimeToolExecuteContext } from './runtime-contract.js';\n+import type {\n+ JsonObject,\n+ RuntimeTool,\n+ RuntimeToolExecuteContext,\n+} from '@webmcp-loom/runtime';\n \n const CITY_IDS: readonly CityId[] = ['hakone', 'kyoto', 'nara', 'osaka', 'tokyo'];\n const ACTIVITY_TAGS: readonly ActivityTag[] = ['culture', 'food', 'nature', 'nightlife', 'shopping'];", "status": "modified"}, {"additions": 6, "deletions": 1, "filename": "apps/travel-showcase/tsconfig.build.json", "patch": "@@ -1,7 +1,7 @@\n {\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n- \"composite\": false,\n+ \"composite\": true,\n \"noEmit\": false,\n \"declaration\": true,\n \"declarationMap\": true,\n@@ -14,5 +14,10 @@\n \"src/**/*.test.ts\",\n \"src/app/**\",\n \"vite.config.ts\"\n+ ],\n+ \"references\": [\n+ {\n+ \"path\": \"../../packages/runtime/tsconfig.build.json\"\n+ }\n ]\n }", "status": "modified"}, {"additions": 5, "deletions": 0, "filename": "apps/travel-showcase/tsconfig.json", "patch": "@@ -14,5 +14,10 @@\n \"src/**/*.ts\",\n \"src/**/*.tsx\",\n \"vite.config.ts\"\n+ ],\n+ \"references\": [\n+ {\n+ \"path\": \"../../packages/runtime/tsconfig.build.json\"\n+ }\n ]\n }", "status": "modified"}, {"additions": 1, "deletions": 1, "filename": "packages/runtime/tsconfig.build.json", "patch": "@@ -1,7 +1,7 @@\n {\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n- \"composite\": false,\n+ \"composite\": true,\n \"noEmit\": false,\n \"declaration\": true,\n \"declarationMap\": true,", "status": "modified"}], "message": "feat(integration): register shared travel tools with WebMCP", "sha": "04577dce833419b9e9174864e9ffe7cf636693f9"}], "post_review_commits": ["eb03c3710a932148414062bdb8839eb89dcdf39e", "bff43704d4f980d5422f02b1a74718cc40769dc8", "34ca7d9613f328d79f33e42c3e3742fd9b283bae"], "pr_author": "gnanam1990", "pr_title": "Wire the travel app to the canonical WebMCP surface", "repo_name": "gnanam1990/webmcp-loom"}, "repo": "gnanam1990/webmcp-loom", "snapshot": "snapshots/041d12a854036de96f76c0207cdc73d77ccbf698ae4709f1b25935f313b38f78.pack", "split": "eval", "task_id": "f9be7fc05313be72a84aebf74a232900f3b0e8b69b569253924e243c4cf70a89"} {"base_sha": "623c1105fe6497e2281c3c695c2a9e3abc0853f9", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/QuoteGuards/back/pull/24", "id": "f9d274c97dd0e5cbf5bb4499221b93f731dfc65e3c9acf0437e9c5d3cf8d8350", "preparation_mode": "source-only", "snapshot": {"base_ref": "623c1105fe6497e2281c3c695c2a9e3abc0853f9", "base_sha": "623c1105fe6497e2281c3c695c2a9e3abc0853f9", "body": "", "head_ref": "46c9b8410df64015b2130785406a8d88e4da8e6e", "head_sha": "46c9b8410df64015b2130785406a8d88e4da8e6e", "name": "back", "number": 24, "owner": "QuoteGuards", "pr_url": "https://github.com/QuoteGuards/back/pull/24", "title": ""}}, "head_sha": "46c9b8410df64015b2130785406a8d88e4da8e6e", "metadata": {"group_id": "050ab57ffc02f1b0ef19a7ac4dc4c033865db11888ffa1a642e981a35f105a8f", "snapshot": {"base_sha": "623c1105fe6497e2281c3c695c2a9e3abc0853f9", "external_requirements": [], "head_sha": "46c9b8410df64015b2130785406a8d88e4da8e6e", "objects": 288, "objects_sha256": "87bbf32d17887596a72d520edbabac3ba105af40b9dbe6b307a46d12728333f2", "patch_sha256": "4ca68991494f09a5a170880416d8500b97abc4b7df00ca3f36769d08ca31e2b3"}}, "pr_number": 24, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "bug", "commit_sha": "7ccce106b12f", "description": "Pending email sends were displayed as failures because the history response treated every status other than SENT as failed.", "file_path": "src/main/java/com/project/back/domain/email/dto/EmailHistoryResponse.java"}, {"action_id": "A2", "action_type": "fix", "category": "bug", "commit_sha": "7ccce106b12f", "description": "A failure to save SENT history after an email was sent was caught as a send failure, causing a FAILED history record and an EMAIL_SEND_FAILED error despite successful delivery.", "file_path": "src/main/java/com/project/back/domain/email/service/QuoteEmailService.java"}, {"action_id": "A3", "action_type": "fix", "category": "security", "commit_sha": "7ccce106b12f", "description": "Email-send failure logs exposed the recipient's full email address in plaintext.", "file_path": "src/main/java/com/project/back/domain/email/service/QuoteEmailService.java"}], "commits_under_review": [{"author": "joonho4", "date": "2026-06-22T05:03:27Z", "files": [{"additions": 1, "deletions": 0, "filename": "build.gradle", "patch": "@@ -24,6 +24,7 @@ dependencies {\n implementation 'org.springframework.boot:spring-boot-starter-security'\n implementation 'org.springframework.boot:spring-boot-starter-web'\n implementation 'org.springframework.boot:spring-boot-starter-validation'\n+ implementation 'org.springframework.boot:spring-boot-starter-mail'\n \n implementation 'com.itextpdf:itext7-core:8.0.4'\n implementation 'com.itextpdf:font-asian:8.0.4'", "status": "modified"}, {"additions": 15, "deletions": 1, "filename": "src/main/resources/application.properties", "patch": "@@ -17,4 +17,18 @@ jwt.secret=${JWT_SECRET}\n jwt.access-token-validity-seconds=18000\n \n # CORS\n-cors.allowed-origin=http://localhost:5173\n\\ No newline at end of file\n+cors.allowed-origin=http://localhost:5173\n+\n+# Mail (SMTP)\n+spring.mail.host=${MAIL_HOST:smtp.gmail.com}\n+spring.mail.port=${MAIL_PORT:587}\n+spring.mail.username=${MAIL_USERNAME}\n+spring.mail.password=${MAIL_PASSWORD}\n+spring.mail.properties.mail.smtp.auth=true\n+spring.mail.properties.mail.smtp.starttls.enable=true\n+spring.mail.properties.mail.smtp.connectiontimeout=5000\n+spring.mail.properties.mail.smtp.timeout=5000\n+spring.mail.properties.mail.smtp.writetimeout=5000\n+# 발신자 표시 이름/주소 (미설정 시 username 사용)\n+mail.from-address=${MAIL_FROM:${MAIL_USERNAME}}\n+mail.from-name=${MAIL_FROM_NAME:QuoteGuard}\n\\ No newline at end of file", "status": "modified"}], "message": "Feature:필요한 의존성 및 gmail 세팅 값 추가", "sha": "baa290cae399ef3b695bfb9b4e3c568c61f11788"}, {"author": "joonho4", "date": "2026-06-22T05:04:13Z", "files": [{"additions": 20, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/dto/QuoteEmailRequest.java", "patch": "@@ -0,0 +1,20 @@\n+package com.project.back.domain.email.dto;\n+\n+import jakarta.validation.constraints.Email;\n+import jakarta.validation.constraints.NotBlank;\n+\n+public record QuoteEmailRequest(\n+ @NotBlank(message = \"받는 사람은 필수입니다.\")\n+ @Email(message = \"받는 사람 이메일 형식이 올바르지 않습니다.\")\n+ String to,\n+\n+ @Email(message = \"참조 이메일 형식이 올바르지 않습니다.\")\n+ String cc,\n+\n+ @NotBlank(message = \"제목은 필수입니다.\")\n+ String subject,\n+\n+ String body,\n+\n+ boolean attachPdf\n+) {}", "status": "added"}, {"additions": 3, "deletions": 0, "filename": "src/main/java/com/project/back/global/exception/ErrorCode.java", "patch": "@@ -47,6 +47,9 @@ public enum ErrorCode {\n QUOTE_NOT_EXPIRED(HttpStatus.BAD_REQUEST, \"QUOTE_003\", \"만료된 견적만 재작성할 수 있습니다.\"),\n QUOTE_ACCESS_DENIED(HttpStatus.FORBIDDEN, \"QUOTE_004\", \"본인이 작성한 견적만 접근할 수 있습니다.\"),\n \n+ // Email\n+ EMAIL_SEND_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, \"EMAIL_001\", \"이메일 발송에 실패했습니다.\"),\n+\n // Customer\n CUSTOMER_NOT_FOUND(HttpStatus.NOT_FOUND, \"CUSTOMER_001\", \"존재하지 않는 고객입니다.\"),\n ", "status": "modified"}], "message": "Feature:에러코드 추가 및 이메일 발송 내역 추가", "sha": "ebbeaee1f4e49f89b96419f3d949b9efe7ff91f1"}, {"author": "joonho4", "date": "2026-06-22T05:04:52Z", "files": [{"additions": 62, "deletions": 2, "filename": "src/main/java/com/project/back/domain/document/service/QuoteDocumentService.java", "patch": "@@ -3,10 +3,13 @@\n import com.project.back.domain.document.dto.QuotePdfData;\n import com.project.back.domain.document.dto.QuotePdfRequest;\n import com.project.back.domain.document.pdf.QuotePdfGenerator;\n+import com.project.back.domain.quote.entity.Quote;\n+import com.project.back.domain.quote.entity.QuoteItem;\n import lombok.RequiredArgsConstructor;\n import org.springframework.stereotype.Service;\n \n import java.io.IOException;\n+import java.math.BigDecimal;\n import java.time.LocalDateTime;\n import java.util.List;\n \n@@ -18,9 +21,17 @@ public class QuoteDocumentService {\n \n public QuotePdfData.DocumentResult generatePdf(QuotePdfRequest req) throws IOException {\n QuotePdfData.QuoteInfo quoteInfo = toQuoteInfo(req);\n- byte[] content = pdfGenerator.generate(quoteInfo);\n+ return buildResult(quoteInfo);\n+ }\n+\n+ /** Quote 엔티티로부터 PDF 생성 (이메일 첨부 등 서버 측 발행용) */\n+ public QuotePdfData.DocumentResult generatePdf(Quote quote) throws IOException {\n+ return buildResult(toQuoteInfo(quote));\n+ }\n \n- String fileName = \"견적서_\" + req.quoteNumber() + \".pdf\";\n+ private QuotePdfData.DocumentResult buildResult(QuotePdfData.QuoteInfo quoteInfo) throws IOException {\n+ byte[] content = pdfGenerator.generate(quoteInfo);\n+ String fileName = \"견적서_\" + quoteInfo.quoteNumber() + \".pdf\";\n return new QuotePdfData.DocumentResult(\n fileName,\n content,\n@@ -30,6 +41,55 @@ public QuotePdfData.DocumentResult generatePdf(QuotePdfRequest req) throws IOExc\n );\n }\n \n+ private QuotePdfData.QuoteInfo toQuoteInfo(Quote quote) {\n+ QuotePdfData.CustomerInfo customer = new QuotePdfData.CustomerInfo(\n+ quote.getQuoteCustomer().getCompanyName(),\n+ quote.getQuoteCustomer().getContactName(),\n+ quote.getQuoteCustomer().getEmail(),\n+ quote.getQuoteCustomer().getPhone(),\n+ quote.getQuoteCustomer().getAddress()\n+ );\n+\n+ QuotePdfData.CompanyInfo company = new QuotePdfData.CompanyInfo(\n+ quote.getCompany().getName(),\n+ quote.getCompany().getAddress(),\n+ quote.getCompany().getPhone(),\n+ quote.getCompany().getEmail(),\n+ quote.getCompany().getBusinessNumber()\n+ );\n+\n+ List items = quote.getItems().stream()\n+ .map(this::toPdfItem)\n+ .toList();\n+\n+ return new QuotePdfData.QuoteInfo(\n+ quote.getQuoteNumber(),\n+ quote.getIssuedDate(),\n+ quote.getValidUntil(),\n+ quote.getDeliveryTerm(),\n+ customer,\n+ company,\n+ items,\n+ quote.getSubtotal(),\n+ quote.getDiscountAmount(),\n+ quote.getTaxAmount(),\n+ quote.getTotalAmount(),\n+ quote.getInternalMemo()\n+ );\n+ }\n+\n+ private QuotePdfData.QuoteItem toPdfItem(QuoteItem item) {\n+ return new QuotePdfData.QuoteItem(\n+ item.getSortOrder() != null ? item.getSortOrder() : 0,\n+ item.getProductName(),\n+ item.getSpec(),\n+ item.getQuantity() != null ? item.getQuantity().intValue() : 0,\n+ item.getUnitPrice(),\n+ item.getDiscountRate() != null ? item.getDiscountRate() : BigDecimal.ZERO,\n+ item.getLineTotal()\n+ );\n+ }\n+\n private QuotePdfData.QuoteInfo toQuoteInfo(QuotePdfRequest req) {\n QuotePdfData.CustomerInfo customer = new QuotePdfData.CustomerInfo(\n req.customer().companyName(),", "status": "modified"}, {"additions": 29, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/controller/QuoteEmailController.java", "patch": "@@ -0,0 +1,29 @@\n+package com.project.back.domain.email.controller;\n+\n+import com.project.back.domain.email.dto.QuoteEmailRequest;\n+import com.project.back.domain.email.service.QuoteEmailService;\n+import com.project.back.global.common.ApiResponse;\n+import jakarta.validation.Valid;\n+import lombok.RequiredArgsConstructor;\n+import org.springframework.http.ResponseEntity;\n+import org.springframework.security.core.annotation.AuthenticationPrincipal;\n+import org.springframework.web.bind.annotation.*;\n+\n+@RestController\n+@RequestMapping(\"/api/quotes\")\n+@RequiredArgsConstructor\n+public class QuoteEmailController {\n+\n+ private final QuoteEmailService quoteEmailService;\n+\n+ // 견적서 이메일 발송 (PDF 첨부 옵션)\n+ @PostMapping(\"/{quoteNumber}/email\")\n+ public ResponseEntity> sendQuoteEmail(\n+ @AuthenticationPrincipal Long userId,\n+ @PathVariable String quoteNumber,\n+ @RequestBody @Valid QuoteEmailRequest request) {\n+\n+ quoteEmailService.sendQuoteEmail(quoteNumber, userId, request);\n+ return ResponseEntity.ok(ApiResponse.success(\"이메일이 발송되었습니다.\", null));\n+ }\n+}", "status": "added"}, {"additions": 75, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/service/QuoteEmailService.java", "patch": "@@ -0,0 +1,75 @@\n+package com.project.back.domain.email.service;\n+\n+import com.project.back.domain.document.dto.QuotePdfData;\n+import com.project.back.domain.document.service.QuoteDocumentService;\n+import com.project.back.domain.email.dto.QuoteEmailRequest;\n+import com.project.back.domain.quote.entity.Quote;\n+import com.project.back.domain.quote.repository.QuoteRepository;\n+import com.project.back.domain.user.entity.User;\n+import com.project.back.domain.user.repository.UserRepository;\n+import com.project.back.global.exception.CustomException;\n+import com.project.back.global.exception.ErrorCode;\n+import jakarta.mail.MessagingException;\n+import jakarta.mail.internet.MimeMessage;\n+import lombok.RequiredArgsConstructor;\n+import lombok.extern.slf4j.Slf4j;\n+import org.springframework.beans.factory.annotation.Value;\n+import org.springframework.core.io.ByteArrayResource;\n+import org.springframework.mail.javamail.JavaMailSender;\n+import org.springframework.mail.javamail.MimeMessageHelper;\n+import org.springframework.stereotype.Service;\n+import org.springframework.transaction.annotation.Transactional;\n+import org.springframework.util.StringUtils;\n+\n+import java.io.IOException;\n+import java.nio.charset.StandardCharsets;\n+\n+@Slf4j\n+@Service\n+@RequiredArgsConstructor\n+@Transactional(readOnly = true)\n+public class QuoteEmailService {\n+\n+ private final JavaMailSender mailSender;\n+ private final QuoteRepository quoteRepository;\n+ private final UserRepository userRepository;\n+ private final QuoteDocumentService documentService;\n+\n+ @Value(\"${mail.from-address}\")\n+ private String fromAddress;\n+\n+ @Value(\"${mail.from-name:QuoteGuard}\")\n+ private String fromName;\n+\n+ public void sendQuoteEmail(String quoteNumber, Long userId, QuoteEmailRequest request) {\n+ User user = userRepository.findById(userId)\n+ .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));\n+\n+ Quote quote = quoteRepository.findByQuoteNumberAndCreatedBy(quoteNumber, user)\n+ .orElseThrow(() -> new CustomException(ErrorCode.QUOTE_NOT_FOUND));\n+\n+ try {\n+ MimeMessage message = mailSender.createMimeMessage();\n+ MimeMessageHelper helper = new MimeMessageHelper(\n+ message, request.attachPdf(), StandardCharsets.UTF_8.name());\n+\n+ helper.setFrom(fromAddress, fromName);\n+ helper.setTo(request.to());\n+ if (StringUtils.hasText(request.cc())) {\n+ helper.setCc(request.cc());\n+ }\n+ helper.setSubject(request.subject());\n+ helper.setText(request.body() != null ? request.body() : \"\", false);\n+\n+ if (request.attachPdf()) {\n+ QuotePdfData.DocumentResult pdf = documentService.generatePdf(quote);\n+ helper.addAttachment(pdf.fileName(), new ByteArrayResource(pdf.content()));\n+ }\n+\n+ mailSender.send(message);\n+ } catch (MessagingException | IOException e) {\n+ log.error(\"견적서 이메일 발송 실패 - quoteNumber={}, to={}\", quoteNumber, request.to(), e);\n+ throw new CustomException(ErrorCode.EMAIL_SEND_FAILED);\n+ }\n+ }\n+}", "status": "added"}], "message": "Feature:메일 발송 기능 구현 및 API 추가\n\nPOST /api/quotes/{quoteNumber}/email", "sha": "85c02bf3e6527cb4fcf1f91c23f9f5c31c73a493"}, {"author": "joonho4", "date": "2026-06-22T05:21:54Z", "files": [{"additions": 56, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/entity/EmailSend.java", "patch": "@@ -0,0 +1,56 @@\n+package com.project.back.domain.email.entity;\n+\n+import com.project.back.domain.quote.entity.Quote;\n+import com.project.back.domain.user.entity.User;\n+import jakarta.persistence.*;\n+import lombok.*;\n+import org.hibernate.annotations.CreationTimestamp;\n+\n+import java.time.LocalDateTime;\n+\n+@Entity\n+@Table(name = \"email_sends\")\n+@Getter\n+@NoArgsConstructor(access = AccessLevel.PROTECTED)\n+@AllArgsConstructor(access = AccessLevel.PRIVATE)\n+@Builder\n+public class EmailSend {\n+\n+ @Id\n+ @GeneratedValue(strategy = GenerationType.IDENTITY)\n+ private Long id;\n+\n+ @ManyToOne(fetch = FetchType.LAZY)\n+ @JoinColumn(name = \"quote_id\", nullable = false)\n+ private Quote quote;\n+\n+ @ManyToOne(fetch = FetchType.LAZY)\n+ @JoinColumn(name = \"sent_by\", nullable = false)\n+ private User sentBy;\n+\n+ @Column(name = \"to_email\", nullable = false, length = 255)\n+ private String toEmail;\n+\n+ @Column(name = \"subject\", nullable = false, length = 500)\n+ private String subject;\n+\n+ @Column(name = \"body\", columnDefinition = \"TEXT\")\n+ private String body;\n+\n+ @Enumerated(EnumType.STRING)\n+ @Column(name = \"status\", nullable = false, length = 20)\n+ @Builder.Default\n+ private EmailSendStatus status = EmailSendStatus.PENDING;\n+\n+ @Column(name = \"failure_reason\", length = 500)\n+ private String failureReason;\n+\n+ // 발송 성공 일시 (실패 시 null)\n+ @Column(name = \"sent_at\")\n+ private LocalDateTime sentAt;\n+\n+ // 발송 요청 일시\n+ @CreationTimestamp\n+ @Column(name = \"created_at\", nullable = false, updatable = false)\n+ private LocalDateTime createdAt;\n+}", "status": "added"}, {"additions": 7, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/entity/EmailSendStatus.java", "patch": "@@ -0,0 +1,7 @@\n+package com.project.back.domain.email.entity;\n+\n+public enum EmailSendStatus {\n+ PENDING,\n+ SENT,\n+ FAILED\n+}", "status": "added"}, {"additions": 15, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/repository/EmailSendRepository.java", "patch": "@@ -0,0 +1,15 @@\n+package com.project.back.domain.email.repository;\n+\n+import com.project.back.domain.email.entity.EmailSend;\n+import org.springframework.data.jpa.repository.JpaRepository;\n+import org.springframework.data.jpa.repository.Query;\n+import org.springframework.data.repository.query.Param;\n+\n+import java.util.List;\n+\n+public interface EmailSendRepository extends JpaRepository {\n+\n+ @Query(\"SELECT e FROM EmailSend e JOIN FETCH e.quote \" +\n+ \"WHERE e.sentBy.id = :userId ORDER BY e.createdAt DESC\")\n+ List findBySentByIdWithQuote(@Param(\"userId\") Long userId);\n+}", "status": "added"}], "message": "Feature:메일 발송 이력 엔티티및리포지토리 생성", "sha": "4692f62fb5e7ef69a5571bda0f457ee8494482d8"}, {"author": "joonho4", "date": "2026-06-22T05:26:55Z", "files": [{"additions": 29, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/controller/EmailHistoryController.java", "patch": "@@ -0,0 +1,29 @@\n+package com.project.back.domain.email.controller;\n+\n+import com.project.back.domain.email.dto.EmailHistoryResponse;\n+import com.project.back.domain.email.service.EmailHistoryService;\n+import com.project.back.global.common.ApiResponse;\n+import lombok.RequiredArgsConstructor;\n+import org.springframework.http.ResponseEntity;\n+import org.springframework.security.core.annotation.AuthenticationPrincipal;\n+import org.springframework.web.bind.annotation.GetMapping;\n+import org.springframework.web.bind.annotation.RequestMapping;\n+import org.springframework.web.bind.annotation.RestController;\n+\n+import java.util.List;\n+\n+@RestController\n+@RequestMapping(\"/api/email-history\")\n+@RequiredArgsConstructor\n+public class EmailHistoryController {\n+\n+ private final EmailHistoryService emailHistoryService;\n+\n+ // 내 이메일 발송 이력 조회\n+ @GetMapping\n+ public ResponseEntity>> getMyHistory(\n+ @AuthenticationPrincipal Long userId) {\n+\n+ return ResponseEntity.ok(ApiResponse.success(emailHistoryService.getMyHistory(userId)));\n+ }\n+}", "status": "added"}, {"additions": 38, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/dto/EmailHistoryResponse.java", "patch": "@@ -0,0 +1,38 @@\n+package com.project.back.domain.email.dto;\n+\n+import com.project.back.domain.email.entity.EmailSend;\n+import com.project.back.domain.email.entity.EmailSendStatus;\n+import com.project.back.domain.quote.entity.Quote;\n+\n+import java.time.LocalDateTime;\n+\n+public record EmailHistoryResponse(\n+ Long id,\n+ LocalDateTime sentAt,\n+ String quoteId,\n+ String buyer,\n+ String to,\n+ String subject,\n+ String status,\n+ String failureReason\n+) {\n+ public static EmailHistoryResponse from(EmailSend e) {\n+ Quote quote = e.getQuote();\n+ String buyer = (quote.getQuoteCustomer() != null)\n+ ? quote.getQuoteCustomer().getCompanyName() : null;\n+\n+ // 성공 시 발송 일시, 그 외에는 요청 일시 노출\n+ LocalDateTime occurredAt = (e.getSentAt() != null) ? e.getSentAt() : e.getCreatedAt();\n+\n+ return new EmailHistoryResponse(\n+ e.getId(),\n+ occurredAt,\n+ quote.getQuoteNumber(),\n+ buyer,\n+ e.getToEmail(),\n+ e.getSubject(),\n+ e.getStatus() == EmailSendStatus.SENT ? \"성공\" : \"실패\",\n+ e.getFailureReason()\n+ );\n+ }\n+}", "status": "added"}, {"additions": 66, "deletions": 0, "filename": "src/main/java/com/project/back/domain/email/service/EmailHistoryService.java", "patch": "@@ -0,0 +1,66 @@\n+package com.project.back.domain.email.service;\n+\n+import com.project.back.domain.email.dto.EmailHistoryResponse;\n+import com.project.back.domain.email.dto.QuoteEmailRequest;\n+import com.project.back.domain.email.entity.EmailSend;\n+import com.project.back.domain.email.entity.EmailSendStatus;\n+import com.project.back.domain.email.repository.EmailSendRepository;\n+import com.project.back.domain.quote.entity.Quote;\n+import com.project.back.domain.user.entity.User;\n+import lombok.RequiredArgsConstructor;\n+import org.springframework.stereotype.Service;\n+import org.springframework.transaction.annotation.Propagation;\n+import org.springframework.transaction.annotation.Transactional;\n+\n+import java.time.LocalDateTime;\n+import java.util.List;\n+\n+@Service\n+@RequiredArgsConstructor\n+public class EmailHistoryService {\n+\n+ private final EmailSendRepository emailSendRepository;\n+\n+ @Transactional(readOnly = true)\n+ public List getMyHistory(Long userId) {\n+ return emailSendRepository.findBySentByIdWithQuote(userId)\n+ .stream()\n+ .map(EmailHistoryResponse::from)\n+ .toList();\n+ }\n+\n+ // 발송 결과와 독립적으로 이력을 남기기 위해 별도 트랜잭션으로 커밋\n+ @Transactional(propagation = Propagation.REQUIRES_NEW)\n+ public void record(\n+ User sentBy,\n+ Quote quote,\n+ QuoteEmailRequest request,\n+ EmailSendStatus status,\n+ String failureReason\n+ ) {\n+\n+ EmailSend emailSend = EmailSend.builder()\n+ .quote(quote)\n+ .sentBy(sentBy)\n+ .toEmail(request.to())\n+ .subject(request.subject())\n+ .body(request.body())\n+ .status(status)\n+ .failureReason(truncate(failureReason))\n+ .sentAt(status == EmailSendStatus.SENT ? LocalDateTime.now() : null)\n+ .build();\n+\n+ emailSendRepository.save(emailSend);\n+ }\n+\n+ private String truncate(String message) {\n+\n+ if (message == null) {\n+ return null;\n+ }\n+\n+ return message.length() > 500\n+ ? message.substring(0, 500)\n+ : message;\n+ }\n+}", "status": "added"}, {"additions": 14, "deletions": 2, "filename": "src/main/java/com/project/back/domain/email/service/QuoteEmailService.java", "patch": "@@ -3,6 +3,7 @@\n import com.project.back.domain.document.dto.QuotePdfData;\n import com.project.back.domain.document.service.QuoteDocumentService;\n import com.project.back.domain.email.dto.QuoteEmailRequest;\n+import com.project.back.domain.email.entity.EmailSendStatus;\n import com.project.back.domain.quote.entity.Quote;\n import com.project.back.domain.quote.repository.QuoteRepository;\n import com.project.back.domain.user.entity.User;\n@@ -34,14 +35,20 @@ public class QuoteEmailService {\n private final QuoteRepository quoteRepository;\n private final UserRepository userRepository;\n private final QuoteDocumentService documentService;\n+ private final EmailHistoryService emailHistoryService;\n \n @Value(\"${mail.from-address}\")\n private String fromAddress;\n \n @Value(\"${mail.from-name:QuoteGuard}\")\n private String fromName;\n \n- public void sendQuoteEmail(String quoteNumber, Long userId, QuoteEmailRequest request) {\n+ public void sendQuoteEmail(\n+ String quoteNumber,\n+ Long userId,\n+ QuoteEmailRequest request\n+ ) {\n+\n User user = userRepository.findById(userId)\n .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));\n \n@@ -55,9 +62,11 @@ public void sendQuoteEmail(String quoteNumber, Long userId, QuoteEmailRequest re\n \n helper.setFrom(fromAddress, fromName);\n helper.setTo(request.to());\n+\n if (StringUtils.hasText(request.cc())) {\n helper.setCc(request.cc());\n }\n+\n helper.setSubject(request.subject());\n helper.setText(request.body() != null ? request.body() : \"\", false);\n \n@@ -67,8 +76,11 @@ public void sendQuoteEmail(String quoteNumber, Long userId, QuoteEmailRequest re\n }\n \n mailSender.send(message);\n- } catch (MessagingException | IOException e) {\n+ emailHistoryService.record(user, quote, request, EmailSendStatus.SENT, null);\n+\n+ } catch (MessagingException | IOException | RuntimeException e) {\n log.error(\"견적서 이메일 발송 실패 - quoteNumber={}, to={}\", quoteNumber, request.to(), e);\n+ emailHistoryService.record(user, quote, request, EmailSendStatus.FAILED, e.getMessage());\n throw new CustomException(ErrorCode.EMAIL_SEND_FAILED);\n }\n }", "status": "modified"}], "message": "Feature:이메일 발송 로직 및 이메일 발송 이력 조회 기능 추가\n\nGET /api/email-history 추가", "sha": "46c9b8410df64015b2130785406a8d88e4da8e6e"}], "post_review_commits": ["7ccce106b12f6d95a599c593ebe20d3391a7d38c"], "pr_author": "joonho4", "pr_title": "Feature/quote email", "repo_name": "QuoteGuards/back"}, "repo": "QuoteGuards/back", "snapshot": "snapshots/050ab57ffc02f1b0ef19a7ac4dc4c033865db11888ffa1a642e981a35f105a8f.pack", "split": "eval", "task_id": "f9d274c97dd0e5cbf5bb4499221b93f731dfc65e3c9acf0437e9c5d3cf8d8350"} {"base_sha": "4bb970c0becc9cc4f2487f8442ee1dda7decb40a", "cohort": "retained", "context": {"canonical_pr_url": "https://github.com/faiscadev/crdtsync/pull/393", "id": "ff03a91fea62bfbcf8fa122081825fce9b31297093c17d4c044e653b206207f3", "preparation_mode": "source-only", "snapshot": {"base_ref": "4bb970c0becc9cc4f2487f8442ee1dda7decb40a", "base_sha": "4bb970c0becc9cc4f2487f8442ee1dda7decb40a", "body": "", "head_ref": "aca08038b4a9977c09afaf327a38d2101bd9c5e9", "head_sha": "aca08038b4a9977c09afaf327a38d2101bd9c5e9", "name": "crdtsync", "number": 393, "owner": "faiscadev", "pr_url": "https://github.com/faiscadev/crdtsync/pull/393", "title": ""}}, "head_sha": "aca08038b4a9977c09afaf327a38d2101bd9c5e9", "metadata": {"group_id": "11e288aa01d68a455fdbafd9b22e117e0d3a6f87cf0cf903d6b8b74f9a3369a1", "snapshot": {"base_sha": "4bb970c0becc9cc4f2487f8442ee1dda7decb40a", "external_requirements": [], "head_sha": "aca08038b4a9977c09afaf327a38d2101bd9c5e9", "objects": 431, "objects_sha256": "1d7f75a1394f9a1092a9b76a41d432e3246e6a3e96ceb2d269982bc1e95d0143", "patch_sha256": "6331d0aaa06a83cebb6e8e6515f5de023e2f947e00eb7f01144d6144178c884b"}}, "pr_number": 393, "references": {"actions": [{"action_id": "A1", "action_type": "fix", "category": "documentation", "commit_sha": "6bb9b4450aa6", "description": "The diff documentation incorrectly claimed that channels bind only on the room leader. A caught-up follower can bind a channel and answer a branch diff from its own state, where a leader-held named branch is absent.", "file_path": "crates/server/src/lib.rs"}, {"action_id": "A2", "action_type": "improvement", "category": "documentation", "commit_sha": "6bb9b4450aa6", "description": "The branch-diff documentation omitted that sides resolve left to right. When both sides fail, the first side determines the returned error and can now determine the wire error code.", "file_path": "crates/server/src/lib.rs"}, {"action_id": "A3", "action_type": "improvement", "category": "other", "commit_sha": "6bb9b4450aa6", "description": "The empty-main regression test checked only the number of changes, so it could pass with the wrong change. It did not verify that the written branch produces an Added register at the expected path.", "file_path": "crates/server/tests/branch_state_taxonomy.rs"}, {"action_id": "A4", "action_type": "fix", "category": "documentation", "commit_sha": "0dad283695ad", "description": "The C53 tracking entry incorrectly claimed that a clipped shared base still makes branch diffs report a wrong addition and publish freeze truncated state. The current seam refuses both; the remaining consequence is an incomplete branch read.", "file_path": "KANBAN.md"}], "commits_under_review": [{"author": "vieiralucas", "date": "2026-08-09T00:28:58Z", "files": [{"additions": 16, "deletions": 0, "filename": "DECISIONS.md", "patch": "@@ -7,6 +7,22 @@ Log of design changes to [ARCHITECTURE.md](ARCHITECTURE.md) that implementation\n The entries below (2026-07-02) are a backfill: design changes made during the v0.1→v0.2 build that predate this log, recovered from the sessions and commit history.\n \n \n+## 2026-08-08 · C51 branch state taxonomy · a branch that cannot be read and a branch that is not there are different answers, and an unwritten room's `main` is neither\n+\n+**Changed:** nothing in ARCHITECTURE. §Schema-Aware Diff already rules that \"an archived side that cannot be decoded refuses the query without closing the connection\"; this makes the *branch* half of the diff seam obey it, where it had been answering the same condition as a missing name. Logged here for the public-surface addition, the wire answer that moves, and the deviation below.\n+\n+**The collapse.** `Hub::materialize_branch` answered `Option>`, and one `None` stood for three unrelated facts about a `(room, branch)` stream: a name the room's branch registry does not hold; a branch it *does* hold whose base this node cannot read — a durable snapshot base that no longer decodes, or a live-log fork whose shared base `main`'s retained log no longer covers; and `main` on a room this node holds no replica for, which is every subscribed-but-never-written room. `Hub::diff_branches` mapped all three to `DiffError::UnknownBranch`, so the wire told a client that a branch `BranchList` enumerates does not exist, and that a room with no ops has no `main`.\n+\n+**Why widening the success case was not available.** The publish path reads the same seam and *correctly* declines each `None`: it writes what it folds straight over the target branch's base and captures it as a permanent named version, so folding an unreadable stream into a fresh document freezes an empty replica durably. Refusing is recoverable; the capture is not. So the three had to be **told apart**, not merged — the seam answers `BranchState { State | Empty | Absent | Unreadable }`, the diff maps each to what it means, and `publish` takes `State` alone.\n+\n+**The mapping, and what each answer says.** `Absent` is the `DiffError::UnknownBranch` it always was — a name the client can correct. `Unreadable` is a new `DiffError::UnreadableBranch(name)` surfacing as `ErrorCode::Internal`: no request the client can phrase gets past it, which is the same reading the version seam already takes of an archived side it cannot decode. `Empty` is the empty document, narrowed by the reader's projection like any other side. **Neither `Internal` answer closes the connection** — a diff's sides are archived or reconstructed state, and one being unreadable is a fault the channel's live stream survives (C27's ruling, which the Unit 7b entry below predates).\n+\n+- **Deviation from the filing, stated.** C51 proposed mapping unreadable onto `DiffError::Decode`. A named variant was taken instead: the clipped-shared-base flavour is not a decode failure at all, the variant names *which* branch is unreadable, and `Decode` keeps meaning the re-decode inside `diff_states`. The wire code is the same either way, so this costs a client nothing and an operator a better message.\n+- **`Empty` is a claim about this node, not about the room.** The diff takes no leader redirect, so every answer is local. A channel only binds where this node serves the read itself — the room's leader, promoted or not — and there the live stream is served empty too, so the change list stays the diff of two states that reader would itself have been handed. Gating the diff on `holds_room` instead would refuse exactly the subscribed-but-never-written room this unit exists to serve. The routing is the missing piece and is filed as **C99**, beside the same question C33 raises for `VersionFetch`.\n+- **Two dated entries below are superseded on their error taxonomy** and are left as written: 2026-07-14 (Unit 7b) says a decode fault is `internal`, *closing* — C27 (#375) made it recoverable — and both it and 2026-07-08 (Unit 7) enumerate a `DiffError` that is now four variants.\n+\n+**Tested** in `crates/server/tests/branch_state_taxonomy.rs` (7): the absent name still `NotFound`, an empty room's `main` both as a wire self-diff and against a branch written before `main` ever was, and the unreadable answer in both flavours — a damaged durable base, told from absence at the hub seam and reaching the wire as `Internal`, and the flavour needing no damage, a live-log fork whose shared base a routine `compact` has passed, with a control that the same fork diffs fine before the floor moves — plus, on each of the two inputs the diff now answers differently, the publish refusing both. → *Server / Branches, Diff — one seam, four answers, and only one of them publishable.*\n+\n ## 2026-08-08 · C2 cross-zone atomic groups · a commit is cut to one atomic transaction per zone, not refused for straddling two\n \n **Changed:** ARCHITECTURE §Scope Constraints gains the enforcement paragraph for the *zone* half of \"a Tx must stay within one branch, one zone, one schema version\" — until now the only enforced constraint on that line was the member cap. No wire change, no signature change: a commit still returns `Vec` and the ops still carry `Tx { id, count }` per member.", "status": "modified"}, {"additions": 8, "deletions": 6, "filename": "KANBAN.md", "patch": "@@ -30,6 +30,8 @@ Element + Map are one coupled unit (Map slots hold Elements; Element forwards li\n \n _Derived from code + git; a convenience view, not the source of truth._\n \n+**C51 — a branch whose durable base this node cannot read is reported as a branch that does not exist (crates/server) — DONE (#PRNUM).** Filed by review during C27 (#375) as reasoned-not-reproduced; **all three cases reproduced first**, each as a failing test before a line of the fix. `Hub::materialize_branch` answered `Option>`, and its `None` stood for three unrelated facts about a stream: a name the room's branch registry does not hold; a branch it *does* hold whose base this node cannot read — a durable snapshot base that no longer decodes, the corruption C15's version guard exists for, or — since C60 (#386), over the defect C88 files — a live-log fork whose shared base `main`'s compaction has dropped; and `main` on a room this node holds no replica for, which is every subscribed-but-never-written room. `Hub::diff_branches` mapped all three to `DiffError::UnknownBranch`, so the wire answered `NotFound \"unknown branch draft\"` for a branch `BranchList` enumerates and `NotFound \"unknown branch main\"` for a room that simply has no ops yet — both measured at the wire, the second off nothing but a `Subscribe`. **The three had to be told apart rather than merged**, which is what made it more than a widened success case: the publish path reads the same seam and *correctly* declines to freeze an empty replica over the branch it names, so admitting the middle case there would trade a wrong error message for silent durable loss. `materialize_branch` now answers a four-way `BranchState` (`State` / `Empty` / `Absent` / `Unreadable`). The diff seam maps `Absent` to the `DiffError::UnknownBranch` it always was, `Unreadable` to a new `DiffError::UnreadableBranch(name)` surfacing as `Internal` — the code the *version* seam already gives an archived side it cannot read, and neither closes the connection — and `Empty` to the empty document an unwritten room's `main` genuinely is, narrowed by the reader's projection like any other side. `publish` takes `State` alone, so both of its refusals stand unchanged, pinned as tests rather than left to the enum. **One deviation from the filing's fix direction, stated:** it proposed mapping unreadable onto `DiffError::Decode`; a named variant was taken instead, because C88's clipped shared base is not a decode failure and the variant names *which* branch is unreadable, while `Decode` keeps meaning what it says — the re-decode inside `diff_states`. **The residue the filing named is filed rather than covered, as C99**: the diff seam takes no read redirect, so on a follower — which replicates `main` alone — a branch the leader holds is genuinely absent locally, and the honest local answer is the misleading one. That needs the read-routing a diff request does not carry, which is the design C33 owns for the version fetch, so it is the same unit's question and not this one's. Spec `crates/server/tests/branch_state_taxonomy.rs` (7): the absent name still `NotFound`, an empty room's `main` both as a self-diff at the wire and against a branch written before `main` ever was, and the unreadable answer in both of its flavours — a genuinely damaged durable base, told from absence at the hub seam and surfacing as `Internal` at the wire, and the flavour that needs no damage at all, a live-log fork whose shared base a routine `compact` has passed, with a control that the same fork diffs fine before the floor moves — plus, on each of the two inputs the diff seam now answers *differently*, the publish refusing both, which is the constraint the split must not break. → *Server / Branches, Diff*.\n+\n **C16 — the reveal back-fill's batch dedup dropped the copy that was zone-protected (crates/server) — DONE (#391).** Filed by cold review during C11 (#359) as reasoned-not-reproduced; **reproduced, and the filing's reachability claim was wrong in the direction that made it look narrower than it is.** The live fan-out's reveal prefix force-stamps every shell and back-filled op with the placing move's zone precisely so a per-channel `zone_filter` cannot drop the content while keeping the shell. C11 made the back-fill skip an op the delivered batch already carries — right, since a second untagged copy takes the batch's tagged one out of its transaction's count — but the surviving copy is then the *batch's*, stamped in the partition its author resolved at emit time. `zone_of_op` resolves a tree op against the live tree, and within one commit an edit inside a node precedes the move that relocates it, so the edit takes the partition the node is moving **out of** while the move takes the destination's: a channel scoped to the destination zone kept the shell, the historical back-fill and the move, and dropped the batch's own edit — a materialised node the reader never finishes filling, diverging permanently from a fresh joiner. **C74 did not close it.** C74 changed how *governing-region* ops (Ranged, ACL) derive their partition; a tree op still takes the partition of the container it targets, resolved against the tree as it stands when the op is emitted, which is the whole mechanism. **Reachability is wider than filed: the shape does not need a named branch.** The filing reasoned that a cross-zone move is only un-gated on a branch (`handle_ops` gates `batch_zone_crossings` on `branch == MAIN_BRANCH`), but Zones-4's capability token admits exactly one crossing on `main`, and the batch riding that token may carry any number of *non*-crossing edits inside the moved node — an edit that moves a node the destination zone already holds into the revealed node crosses nothing, so one token authorizes the whole batch. That is the regression fixture: a card born in `/board` (za, doc-ACL-denied to the reader) carrying a private grandchild, a pin already in `/notes/pub` (zb, readable), one atomic transaction moving the pin into the card and then the card into `/notes/pub`, and a reader scoped to zb who reads `/notes` but not `/notes/priv`. **The first cut re-stamped from the move's envelope and a cold review reproduced a second hole of the same shape, which is why the ruling is not \"stamp the batch copy too\".** A *nested* reveal has two born-denied nodes in one batch, and the move that places the inner one into the outer is emitted while the outer still sits at its origin — so its envelope names the origin partition, and the inner **shell** derived from it was dropped by a destination-scoped channel while the outer's survived. Measured on the same fixture with `x`,`y` born denied inside `/notes/priv` and `card` denied in `/board`: two shells delivered instead of three, `x` never materialised, bob's tree frozen short of the author's. The same derivation also made the dedup's choice of which shell's zone to record depend on `reveal_ops`' element-id sort order, so an op `origin/main` delivered could be withheld. **Ruling: a relocated node's partition is the one it *lands in*, read off the tree the stream serves once the batch is folded — not the one its move's envelope names.** An envelope carries the partition its author resolved when the op was emitted, which is a statement about ordering inside a transaction, not about where the subtree ends up; the folded tree gives every node in one relocated subtree the same answer whatever order the transaction emitted its moves in. So `moved_nodes` resolves each node through the fan-out's own element-path index, and the shell, its back-fill, and the batch's surviving copy of any op the back-fill would have carried all ride that partition. A node the served tree does not resolve keeps its move's answer, the only other partition claim available. The re-stamp is per-recipient (the batch is cloned by `retain_atomic_cloned` before it), so no other recipient's verdict moves; the recipient's per-zone clock advances in the destination partition, which is where the content now lives, and `mint_floor` maxes the partition clock with the replica's own global high-water so a clock left short elsewhere cannot collide. Zone isolation does not move — the re-stamped set is a strict subset of what `reveal_backfill` already yields under the same per-recipient read gate, stamped in the same partition — and the landing partition is resolved under the room's *governing* schema, which is the id space a channel's zone scope was itself resolved in, where an author's envelope only coincidentally is. The `registry.rs` comment claimed more than either derivation supports (that a shell never rides where its placing move is dropped, which is a claim about an op keeping its own envelope) and now states what holds: a revealed node's shell and its contents travel together or not at all. Scope is `main`: `reveal_backfill` reads `main`'s log and document, so on a branch stream the back-fill and the batch never intersect — the branch half is C85's. Spec `crates/server/tests/reveal_zone.rs` (4), pinning the preconditions beside the outcomes — the two ops must carry different partitions, and (since C2 cuts a commit into one atomic transaction per partition) they are two groups, so the co-travel is the only thing keeping them on one channel — plus two controls: a reader no reveal fires for is not re-stamped, and a channel scoped to the partition the node *leaves* is told nothing of it rather than handed content it can never place, which is the fail-closed mirror of the defect and the one behaviour this changes for a reader `origin/main` served. → *Server / Fan-out*.\n \n **C2 — a cross-zone atomic group was emitted straddling both zones, and lost its atomic view at every zone-scoped subscriber (crates/core) — DONE (#390).** ARCHITECTURE §Scope Constraints has always said \"a Tx must stay within one branch, one zone, one schema version\", and §Not Shipped lists cross-zone txs outright; only the member cap on that line was enforced. `zone_of_op` stamps each op with the partition of the region it *governs* (C74), and `tag_atomic` then put **one** group id on every op of a commit whatever partition each fell in — so `atomic_transact` emitted a group no zone-scoped subscriber can receive whole: its subscription withholds the other partition's members and the seam destrands (C11) the survivors, so the group loses its atomicity at exactly the recipients zones exist to serve, while a full-doc subscriber keeps it. **The ruling (taken here, logged in DECISIONS 2026-08-08): split at the mint** — a commit closes one atomic transaction per zone partition its ops fall in, each id derived from its own members' sequences and each key spent at the author. A commit wholly inside one partition, which is every commit in a document declaring no zones, is byte-for-byte the group it always was. **Refusing the straddle at emit was rejected:** it has no honest landing place — the existing `emit_stamped` refusal drops the op and changes no state, so that shape would leave a *partially applied* intention, and refusing the whole commit needs either a rollback of state already applied as it was made or a fallible `atomic_transact` across core/C ABI/wasm/Python/Go, while buying the zone-scoped subscriber nothing the split does not (its delivered set is identical either way). A refusal costs the caller their edits; the split costs them atomicity *across* zones, which was never offered. The precedent is the cap on the same line of the same section — enforced at the mint by degrading (a group past it streams untagged, \"a non-atomic transaction rather than a frame every peer rejects\") — and the split is that treatment, gentler: per-zone atomicity instead of none. **Fix:** `Document::tag_atomic` buckets the commit's ops by `op.zone` and tags each bucket as its own group; the `MAX_TX_MEMBERS` range check moves with it, so it bounds a partition rather than the commit, and a partition outside the range streams untagged as before. No wire change, no signature change — every binding still passes `Vec` through. The ambiguous case is read off the envelope rather than re-derived: a mark whose anchors land in two zones names no partition (C74/C82) and groups with the root partition, which is a partition like any other here. Destranding is untouched and stays the floor — the doc-ACL read filter cuts on paths no group aligns to, and the wire admits a straddling group from a peer whose emitter does not cut — so C11's suites (`crates/core/tests/state_project_tx.rs`, `crates/server/tests/filter_split_tx.rs`) now assemble their straddling group by hand instead of from a local commit. Spec: `crates/core/tests/zone_tx_split.rs` (11 — the straddle emitting one group per zone with per-partition counts and distinct ids; a one-zone commit and an unpartitioned one each still a single group; the root partition taking a group of its own; a straddling commit still emitting every edit and converging; the zone cut running *between* groups rather than through one, so the surviving group reaches its subscriber tagged and holds until whole; the ambiguous mark joining the root group, with an agreeing-anchor control; a stray of *either* minted key landing at the author; the cap bounding a partition rather than the commit; a cross-zone undo intention replaying through the same cut), plus an end-to-end case in `crates/server/tests/filter_split_tx.rs` driving the real `Registry` and zone filter with the *emitter's* uncut output. ARCHITECTURE §Scope Constraints now states the enforcement point, and that read scope is deliberately not a constraint dimension. Cold review filed two residuals, both pre-existing and raised in consequence rather than in kind: **C93** (a one-member partition mints a spendable `resolved_tx` key for no atomicity — routine now that a straddling commit produces singletons; not a divergence, and the fix is a ruling about the *cap*) and **C97** (`set_schema` inside an open transaction re-indexes the zone ids the commit is cut on). The third shape — an `XmlMove` and an edit inside the moved node taking different partitions in one commit — is **C16**'s, already open. → *Transactions / Scope Constraints*.\n@@ -149,7 +151,7 @@ _Derived from code + git; a convenience view, not the source of truth._\n \n **Webhooks** — **Webhooks — outbound `EventSink` over the engine event bus (server) — DONE (#253).** Realizes the §Versioning \"event bus = webhook substrate\" item — the event bus (#191) built for exactly this. `WebhookSink` (`crates/server/src/webhook.rs`) is the second built-in `EventSink` after `AutoVersionSink`: on each room-bearing lifecycle event it serializes a JSON body and `try_send`s it to a bounded (1024) mpsc queue that a separate spawned reqwest worker drains, POSTing **off the hot path** — `on_event` never blocks or panics the hub commit path, so a slow/failing/absent endpoint can't stall emission or the op path. **Delivery = best-effort, at-most-once, no cross-restart ordering:** a full queue drops the event, a failed POST (transport/timeout/non-2xx) is logged and never retried, a single serial worker keeps in-run FIFO. **Worker placement:** the registry actor's `current_thread` runtime has no I/O reactor, so the worker is spawned on the main multi-thread runtime in `serve_with_authorizer` (before the registry thread); the sink carries only the channel `Sender` (Send) into the registry thread to register on the hub. **Event JSON:** `{\"type\": \"\", …}` — `version-created {room,name}` / `version-renamed {room,from,to}` / `version-deleted {room,name}` / `compacted {room,floor}` / `subscribed {room}` / `after-restore {room,branch}` / `before-publish {room,branch}`; byte names as UTF-8 (lossy for non-UTF-8, as elsewhere); roomless connect/disconnect + reserved `before-migration` filtered out (same room-bearing filter as `AutoVersionSink`). Optional shared secret in the `X-Crdtsync-Webhook-Secret` header (over TLS, never the body). **Opt-in:** `ServeConfig.webhook: Option`, `main.rs` reads `CRDTSYNC_WEBHOOK_URL` / `CRDTSYNC_WEBHOOK_SECRET`; unset ⇒ no sink, no worker, zero per-event cost (mirrors the optionally-wired admin plane). Server adds `reqwest` (rustls TLS) + `serde`, neither reaching core. Server-only diff (no `crates/core/src` → CI miri non-required/unaffected); spec `crates/server/tests/webhook.rs` (4, hermetic loopback axum capture server: shape+secret header, compaction floor + no-secret-header, no-sink-no-delivery, dead-endpoint-past-capacity never blocks/panics). Design in DECISIONS (2026-07-12). → *Versioning / Debugging (event bus = webhook substrate)*.\n \n-**Branches** — **Branches Unit 7 — schema-aware branch/version diff (server) — DONE (#251).** The last branch-layer unit: a diff between two branch HEADs / named-version snapshots, computed by feeding two decoded snapshots into the already-built core diff engine (6a-v `core::path::diff`) — no new diff semantics. `Hub::diff_versions(room, a, b) -> Result, DiffError>` decodes both named versions' captured `version_state` and runs `path::diff`; `Hub::diff_branches(room, a, b)` materializes each branch via the existing `materialize_branch` (Unit 3/4 shared base + tail, or a snapshot fork's owned base; `main` via `export_room`) then diffs — so a branch against its fork source yields only the divergence. A shared `diff_states` helper decodes two encoded states and runs the engine. Edge cases are clean errors, never panics: an unknown version → `DiffError::UnknownVersion(name)`, unknown branch → `DiffError::UnknownBranch(name)`, an encoded state that does not decode → `DiffError::Decode`; a snapshot against itself → empty. Schema-aware = reuse the existing `Change` set + `diff.rs` renderers (text char-level / xml structural / map·register·counter·marks value diffs) unchanged — no missing renderer case surfaced. **Exposure decision:** the server-side `Hub::diff_*` computation + its test coverage is the unit; returning a diff to a *client* needs a new wire frame or an admin-plane route (the same client-wire-vs-admin question as Unit 6b), so the client/SDK query surface is deferred to **Branches Unit 7b — diff query surface** (below). Server-only diff (no `crates/core/src` → CI miri non-required/unaffected); spec `crates/server/tests/branch_diff.rs` (9: value/text/structural-add/list-insert version diffs, self-diff empty, unknown version/branch errors, branch-vs-fork-source divergence). Design in DECISIONS (2026-07-12). **With Unit 7 done the branch layer is functionally complete** — the remaining branch items are the two gated exposure follow-ons (6b branch-management SDK, 7b diff query surface — both on the client-wire-vs-admin-plane decision) + cross-branch merge (out of v0.x, ARCHITECTURE line 636). → *Versioning and Branches / Schema-Aware Diff*.\n+**Branches** — **Branches Unit 7 — schema-aware branch/version diff (server) — DONE (#251).** The last branch-layer unit: a diff between two branch HEADs / named-version snapshots, computed by feeding two decoded snapshots into the already-built core diff engine (6a-v `core::path::diff`) — no new diff semantics. `Hub::diff_versions(room, a, b) -> Result, DiffError>` decodes both named versions' captured `version_state` and runs `path::diff`; `Hub::diff_branches(room, a, b)` materializes each branch via the existing `materialize_branch` (Unit 3/4 shared base + tail, or a snapshot fork's owned base; `main` via `export_room`) then diffs — so a branch against its fork source yields only the divergence. A shared `diff_states` helper decodes two encoded states and runs the engine. Edge cases are clean errors, never panics: an unknown version → `DiffError::UnknownVersion(name)`, unknown branch → `DiffError::UnknownBranch(name)`, an encoded state that does not decode → `DiffError::Decode`; a snapshot against itself → empty. *(Superseded by C51: `materialize_branch` answers a four-way `BranchState`, so a branch this node holds but cannot read is `DiffError::UnreadableBranch(name)` rather than `UnknownBranch`, and `main` on a room with no replica is the empty state.)* Schema-aware = reuse the existing `Change` set + `diff.rs` renderers (text char-level / xml structural / map·register·counter·marks value diffs) unchanged — no missing renderer case surfaced. **Exposure decision:** the server-side `Hub::diff_*` computation + its test coverage is the unit; returning a diff to a *client* needs a new wire frame or an admin-plane route (the same client-wire-vs-admin question as Unit 6b), so the client/SDK query surface is deferred to **Branches Unit 7b — diff query surface** (below). Server-only diff (no `crates/core/src` → CI miri non-required/unaffected); spec `crates/server/tests/branch_diff.rs` (9: value/text/structural-add/list-insert version diffs, self-diff empty, unknown version/branch errors, branch-vs-fork-source divergence). Design in DECISIONS (2026-07-12). **With Unit 7 done the branch layer is functionally complete** — the remaining branch items are the two gated exposure follow-ons (6b branch-management SDK, 7b diff query surface — both on the client-wire-vs-admin-plane decision) + cross-branch merge (out of v0.x, ARCHITECTURE line 636). → *Versioning and Branches / Schema-Aware Diff*.\n \n **Branches** — **Branches Unit 6b — branch-management client-wire surface (core + server + FFI/Go/Python) — DONE (#275).** Resolves the 2026-07-14 Q2 design gate: app-facing branch ops ride **new in-band client-wire frames**, not the admin HTTP plane (that plane stays reserved for operator observability). Mirrors the Version* frame set for branches. **Core (`protocol.rs`, tags 27–33):** `BranchList { room }` → `Branches { room, branches: Vec }` (`BranchInfo { name, fork_point, head, published }` — what a client needs to enumerate + act); mutations `BranchFork { room, name, from_branch }` (forks off the source's HEAD, `fork_branch` with `at = u64::MAX` clamped to head), `BranchForkFromVersion { room, name, version }`, `BranchRestore { room, name, version }`, `BranchPublish { room, published }`, `BranchDelete { room, name }`. **Room-keyed, not channel-keyed** (unlike Version*, which rides a subscribed channel) — branch management is a room-level operation a client runs *before* it holds any subscription (e.g. list-to-pick-which-to-subscribe); the diff-query frame (7b) fits this same room/version-keyed shape. Hand-rolled codec, total decode (round-trip + truncation + bogus-count + distinct-tag tests). `ClientSession` frames each request and folds a `Branches` reply into a per-room view. **Server (`session.rs`):** each frame dispatches to the existing `Hub` branch seam, gated by the **version-management authz tier** (doc-ACL abstains, deployment+schema tiers decide — a branch op is a room-management action, no new authz axis); a read lists locally, a mutation is leader-redirected then replies with the fresh set; unauthenticated → violation, denied → recoverable `Forbidden`, a persist error → `internal`, never a panic. **SDK (full 4-way fan-out):** FFI (`crdtsync_client_list_branches`/`_fork_branch`/`_fork_branch_from_version`/`_restore_branch`/`_publish_branch`/`_delete_branch` + `_branch_count`/`_branch_at` getters — cbindgen header regenerated, symbol-assert extended), Go `(*Client).ListBranches`/`ForkBranch`/… + `Branch` struct, Python `Client.list_branches`/… + `Branch` NamedTuple, wasm `listBranches`/`forkBranch`/… + `branches` → `{name, forkPoint, head, published}[]` (`crates/wasm`, the wasm-pack standalone crate). **Core-touching (`protocol.rs`) → CI Miri gates the PR**; targeted core + FFI Miri clean locally. Specs: `crates/core/tests/protocol_branches.rs` (8), `client_branches.rs` (5), `crates/server/tests/branch_ops.rs` (9), FFI `client.rs` branch round-trip, Go/Python/wasm marshal tests. Local correctness review (medium) clean. Design in DECISIONS (2026-07-14). → *Versioning and Branches*.\n \n@@ -437,14 +439,16 @@ scalar / counter / register / element / map (#22–#27), list Fugue (#24), text\n - **Cluster Unit 7b — gossip failure detection (SWIM suspicion + incarnation refutation) — DONE (#272). THE LAST CLUSTER UNIT — the distributed-cluster epic (§Horizontal-Scaling) is COMPLETE.** 7a converged the member set but every member was *optimistically live*; 7b makes the gossip layer detect and disseminate failure, feeding 6a's liveness so a dead node is excluded from room leadership **cluster-wide**, not just by whoever's relay link to it dropped. **Wire (core `protocol.rs`, breaking tag-26 change, pre-release, no migration):** `Message::Gossip`'s member tuple widens to `(node_id, advertise_addr, incarnation: u64, state)` where `state` is `MemberState { Alive, Suspect, Dead }` (a tag byte 0/1/2; `MemberState` derives `Ord` least-to-most-suspicious so `Dead > Suspect > Alive` is the merge tie-break). Decode total (bad state tag → `BadTag`, truncation/over-count/trailing → error, never a panic). **Detection (`membership.rs` + `gossip.rs`, reuses the gossip exchange — no separate detector socket):** a successful round is first-hand proof alive (`note_gossip_reachable`); a failed round counts toward suspicion (`note_gossip_unreachable`) — `SUSPECT_AFTER_FAILURES=3` failed rounds → `Alive→Suspect`, `DEAD_AFTER_FAILURES=6` → `Suspect→Dead`. Count-based not wall-clock, so the state machine is deterministic + test-drivable. **Merge (`merge_liveness`, SWIM anti-entropy):** higher incarnation always wins, equal incarnation the more-suspicious state wins; commutative + idempotent (order-independent convergence). **Refutation:** a node told it is itself `Suspect`/`Dead` bumps its incarnation above the received one and re-asserts `Alive` (`refute_if_stale`) — the correction outranks the stale suspicion everywhere, so a live node is never stuck dead. **Wired into 6a:** the gossip signal and the 6a relay-link signal are **UNIONED** (`is_live` = relay-up AND not-gossip-Dead) — neither masks the other (a gossip-`Alive` doesn't resurrect a relay-down node; a relay reconnect doesn't resurrect a gossip-`Dead` node — only a refutation does); a `Suspect` still routes optimistically, only `Dead` excludes from `effective_primary_for`, so failover fires on a confirmed death and a refuted/recovered node reclaims its rooms. **Core-touching (`protocol.rs`) → CI Miri gates the PR**; detection/merge/refutation Miri-clean. Tests: `crates/core/tests/protocol_gossip.rs` (12 — every-state round-trip, bad-state-tag/truncation/over-count/trailing errors, distinct tags, suspicion ordering); `crates/server/tests/gossip.rs` (24 — suspect→dead escalation + failover, both-survivors-independent, success-clears-suspicion, refutation-restores + overrides-Dead, higher-incarnation-wins, equal-incarnation-Dead>Suspect>Alive, order-independent merge, cross-node dissemination without a dropped link, relay-vs-gossip union both directions, single-node inert; one loopback socket `#[cfg_attr(miri, ignore)]`). Design in DECISIONS (2026-07-14). **Deferred (documented, non-blocking — see Revisit):** SWIM indirect probing (ping-req via k relays), member *reaping* (Dead stays in the set marked down), 7a's late-joiner replication-dial wiring. → *Horizontal Scaling*.\n - **Branch layer remaining (exposure-gated / out-of-scope):**\n - **Unit 6b — branch-management client-wire surface — DONE (#275, see Done).** The 2026-07-14 Q2 gate resolved to **new client-wire frames** (in-band, SDK-native, same-session auth), not the admin plane. `BranchList`/`Branches`/`BranchFork`/`BranchForkFromVersion`/`BranchRestore`/`BranchPublish`/`BranchDelete` (tags 27–33) mirror the Version* set, room-keyed; server handlers wire the `Hub` seams at the version-management authz tier; FFI/Go/Python landed (no wasm SDK exists). Design in DECISIONS (2026-07-14).\n- - **Unit 7b — diff query surface (core + server + FFI/Go/Python/wasm) — DONE (#277). THIS CLOSES THE BRANCH-LAYER CLIENT EXPOSURE (6b management + 7b diff query) — the branch epic's client surface is COMPLETE.** Unit 7 (#251) built the server-side `Hub::diff_versions`/`diff_branches` computation; 7b returns a diff to a *client* over a new client-wire frame, reusing 6b's client-wire-query approach per the user's 2026-07-14 Q2 ruling (app-facing queries ride in-band frames, not the admin plane). **Core (`protocol.rs`, tags 40/41 — deliberately distinct from the 27–33 Branch* block + the Zones sibling's SUBSCRIBE-region tags):** `DiffQuery { room, kind: DiffKind, a, b }` → `DiffResult { room, changes }`. `DiffKind { Versions, Branches }` (tag byte 0/1) selects the state space; `changes` is the **encoded `Change` list** carried as an opaque length-framed `Vec` — the same `encode_changes`/`decode_changes` codec the FFI diff bindings (#232/#113) already marshal, so protocol.rs stays free of diff internals. Room-keyed like Branch* (runnable before any subscription) — **superseded by C27 (#375)**, which made the query channel-keyed because a change list carries the room's own content and the channel is what carries the reader's zone scope. Hand-rolled codec, total decode (round-trip empty/many-change, truncation, bad-kind-tag, trailing, distinct-tag tests). `ClientSession` frames the query and folds a `DiffResult` into a per-room decoded-`Change` view (`diff_query`/`diff`); a malformed change payload → `ClientError::BadDiff`, no view touched. **Errors:** DiffError→client via a new `ErrorCode::NotFound` (wire tag 7) — unknown version/branch is a recoverable Error frame (connection stays open, mirroring a denied branch op); a snapshot that fails to decode → `internal` (server fault, closes). **Server (`session.rs`):** `DiffQuery` gated by the SAME read tier as `BranchList` (`branch_authorized(.., Action::Read)` — a diff is a room-state read, no new authz axis), dispatched per `kind` to `Hub::diff_versions`/`diff_branches`, `Change` list encoded into `DiffResult`; served locally (no leader redirect — a read). Unauthenticated → violation, denied → recoverable `Forbidden`, unknown → `NotFound`, never a panic. **SDK (full 4-way fan-out):** FFI `crdtsync_client_diff_query(client, room, kind:u32, a, b)` + `crdtsync_client_diff_result(client, room, out)` returning the encoded change bytes a binding feeds to the EXISTING `crdtsync_diff_decode` (cbindgen header regenerated, symbol-assert extended, `error_code_discriminant` maps NotFound→7); Go `(*Client).DiffQuery`/`DiffResult` + `DiffKind` consts; Python `Client.diff_query`/`diff` + `DiffKind` IntEnum + `ErrorCode.NOT_FOUND`; wasm `diffQuery`/`diff` (`crates/wasm`) + `ErrorCode::NotFound`. **Core-touching (`protocol.rs`) → CI Miri gates the PR**; targeted core + FFI Miri clean locally. Specs: `crates/core/tests/protocol_diff.rs` (7), `client_diff.rs` (5), `crates/server/tests/diff_query.rs` (7 — version/branch diff matches `Hub`, self-diff empty, unknown version/branch NotFound, read-denied Forbidden, before-auth violation), FFI `client.rs` diff round-trip, Go/Python/wasm marshal+receive tests. Local correctness review (medium) clean. Design in DECISIONS (2026-07-14). → *Versioning and Branches / Schema-Aware Diff*.\n+ - **Unit 7b — diff query surface (core + server + FFI/Go/Python/wasm) — DONE (#277). THIS CLOSES THE BRANCH-LAYER CLIENT EXPOSURE (6b management + 7b diff query) — the branch epic's client surface is COMPLETE.** Unit 7 (#251) built the server-side `Hub::diff_versions`/`diff_branches` computation; 7b returns a diff to a *client* over a new client-wire frame, reusing 6b's client-wire-query approach per the user's 2026-07-14 Q2 ruling (app-facing queries ride in-band frames, not the admin plane). **Core (`protocol.rs`, tags 40/41 — deliberately distinct from the 27–33 Branch* block + the Zones sibling's SUBSCRIBE-region tags):** `DiffQuery { room, kind: DiffKind, a, b }` → `DiffResult { room, changes }`. `DiffKind { Versions, Branches }` (tag byte 0/1) selects the state space; `changes` is the **encoded `Change` list** carried as an opaque length-framed `Vec` — the same `encode_changes`/`decode_changes` codec the FFI diff bindings (#232/#113) already marshal, so protocol.rs stays free of diff internals. Room-keyed like Branch* (runnable before any subscription) — **superseded by C27 (#375)**, which made the query channel-keyed because a change list carries the room's own content and the channel is what carries the reader's zone scope. Hand-rolled codec, total decode (round-trip empty/many-change, truncation, bad-kind-tag, trailing, distinct-tag tests). `ClientSession` frames the query and folds a `DiffResult` into a per-room decoded-`Change` view (`diff_query`/`diff`); a malformed change payload → `ClientError::BadDiff`, no view touched. **Errors:** DiffError→client via a new `ErrorCode::NotFound` (wire tag 7) — unknown version/branch is a recoverable Error frame (connection stays open, mirroring a denied branch op); a snapshot that fails to decode → `internal` (server fault, closes). *(Superseded twice: C27 (#375) made the decode fault recoverable rather than closing, and C51 gave a branch this node holds but cannot read its own `Internal` answer, so `NotFound` now means a name the room does not have and nothing else.)* **Server (`session.rs`):** `DiffQuery` gated by the SAME read tier as `BranchList` (`branch_authorized(.., Action::Read)` — a diff is a room-state read, no new authz axis), dispatched per `kind` to `Hub::diff_versions`/`diff_branches`, `Change` list encoded into `DiffResult`; served locally (no leader redirect — a read). Unauthenticated → violation, denied → recoverable `Forbidden`, unknown → `NotFound`, never a panic. **SDK (full 4-way fan-out):** FFI `crdtsync_client_diff_query(client, room, kind:u32, a, b)` + `crdtsync_client_diff_result(client, room, out)` returning the encoded change bytes a binding feeds to the EXISTING `crdtsync_diff_decode` (cbindgen header regenerated, symbol-assert extended, `error_code_discriminant` maps NotFound→7); Go `(*Client).DiffQuery`/`DiffResult` + `DiffKind` consts; Python `Client.diff_query`/`diff` + `DiffKind` IntEnum + `ErrorCode.NOT_FOUND`; wasm `diffQuery`/`diff` (`crates/wasm`) + `ErrorCode::NotFound`. **Core-touching (`protocol.rs`) → CI Miri gates the PR**; targeted core + FFI Miri clean locally. Specs: `crates/core/tests/protocol_diff.rs` (7), `client_diff.rs` (5), `crates/server/tests/diff_query.rs` (7 — version/branch diff matches `Hub`, self-diff empty, unknown version/branch NotFound, read-denied Forbidden, before-auth violation), FFI `client.rs` diff round-trip, Go/Python/wasm marshal+receive tests. Local correctness review (medium) clean. Design in DECISIONS (2026-07-14). → *Versioning and Branches / Schema-Aware Diff*.\n - _With 6b + 7b done, the branch layer's client surface is **COMPLETE** (subscribe #250, management #275, diff query #277); the only remaining branch work is cross-branch merge (out of v0.x, ARCHITECTURE line 636). Next cs-next replenishment epic: **distributed cluster** is COMPLETE (#272); the ungated frontier (Zones Unit 5 subscribe SDK surface now DONE #281 — the zones epic client surface is COMPLETE) is Schema-Migration Unit 8 or the smaller v0.2 items (webhooks — event-bus #191 substrate done; awareness auth-filter §850)._\n - **STILL GATED** (needs a human/seam ruling — do NOT cut): Unit 9c (repair-closure). **Ungated 2026-07-14** by the server **element-context index** (id→context over the room's document projection, PR#): Zones **1b-ii-b (cross-zone move)** is DONE, and its foundation unblocked Zones **Unit 2 (per-zone lamport + envelope `zone`, DONE #276)** — whose substrate unblocked **Unit 3 (server per-zone streams + zone-scoped subscribe/redaction, DONE #278)**, then **Unit 5 (zone-scoped subscribe SDK surface, DONE #281 — zones epic client surface COMPLETE)** — and Unit 8 type-scope + container-field migration filters (the id→declared-type resolution the fan-out seam lacked now layers on the same `element_paths` projection). After the branch layer: the **distributed-cluster** epic (§Horizontal-Scaling, also designed → ungated) is the next replenishment.\n \n ---\n \n ## ⏭ Next\n \n+**C99 — a branch diff is answered from whichever node holds the channel, and a follower holds `main` alone (crates/server) — READY, no dependencies. Found during C51, which named it and covered the rest.** `Hub::diff_branches` resolves both sides against local state with no routing gate at all — unlike `Subscribe`, which runs `read_redirect_response` and lets a follower serve only when it holds the room, holds a materialized copy, and its committed watermark has reached the client's floor. Replication carries `main`: a follower holds no branch registry entry for a named branch the leader forked, so C51's `BranchState::Absent` is the *locally honest* answer for a branch that plainly exists, and the client is told `NotFound` for a name `BranchList` on the leader enumerates. C51 deliberately did not widen `Absent` to cover it — locally the branch really is absent, and a seam cannot report a fact it has no way to learn; what is missing is the redirect, not the taxonomy. A channel legitimately bound to `main` on a follower reaches the same wall from the other side, since a diff naming `main` against a named branch has one side the follower can serve and one it cannot. Fix wants the diff to take the read routing `Subscribe` takes — redirect to the leader unless this node can answer both sides — which needs a freshness floor a diff request does not carry, exactly the missing input **C33** identifies for `VersionFetch`; the two want one answer, and a branch diff additionally has to say whether *one* unservable side redirects the whole query. **The `Empty` arm has the same shape and reaches the wire by a different door.** `read_redirect_response` resolves the leader first and returns *serve locally* before it ever consults `holds_room` — that gate is on the follower path alone — so a node **promoted** for a room whose state it never received is the leader, binds the channel, and answers `main` as empty for a room that has content on the node it took over from. What makes that the honest local answer rather than a fresh hole is that the same node serves that channel's live stream empty too, so the change list is still the diff of two states this reader is being handed; C51 declined to re-break the empty answer to paper over it, because a `holds_room` gate on the diff would refuse exactly the subscribed-but-never-written room C51 exists to serve. The routing is the missing piece, in both directions. Distinct from C51's taxonomy, which is about what a node reports for the state it has; this is about which node is asked. → *Server / Branches, Replication*.\n+\n **C98 — the reveal back-fill never replays a revealed node's text, so a live reader materialises an empty run (crates/server) — READY, no dependencies. Found by cold review during C16 (#391), identified by inspection.** `Hub::reveal_backfill` selects the log ops whose target sits in `Document::movable_subtree_containers(node)`, and that set collects each descendant XmlElement's *attrs* and *children* ids only — a Text run's own id is never in it, while `TextInsert`/`TextDelete` target the run. So a node revealed on move-in has its runs **created** and never filled: the `XmlInsertChild { tag: None }` that installs a run targets the children list and is back-filled, the text authored into it while the subtree was private is not, and the live reader holds an empty run where a fresh or snapshot joiner holds the content — the same permanent divergence C16 closes, one op kind over, and the same one the back-fill exists to prevent. The attrs half wants the same look: a run is the case inspection found, but the rule the set encodes is \"containers reachable by the move\", and every op kind that targets something inside a revealed subtree has to be in it or the reader diverges. Not reachable through today's authoring surface — no cursor addresses an already-materialised deep XML node, so a run inside a moved node can only be written by a raw op or by an earlier `insert_text` that the same transaction's move then relocates — which is why C16's fixtures are moves throughout, and why this is filed rather than folded into it. Wants the subtree set to name every container a relocated node carries, with a test that a revealed node's text arrives filled. Sits beside **C85**, which owns the branch axis of the same seam. → *Server / Fan-out*.\n \n **C85 — a branch fan-out synthesizes its reveal shells and their back-fill from `main`'s document (crates/server) — READY, no dependencies. Found during C60 (#386), identified by inspection while closing the index axis it sits beside.** C60 moved the redaction *index* of a `(room, branch)` fan-out onto the branch's own tree. Two co-inputs to the same loop did not move: `Hub::reveal_ops(room, reads)` and `Hub::reveal_backfill(room, node, …)` both project `self.rooms[room].doc` — the live `main` replica — and both **synthesize ops** out of it. Reveal-on-move-in exists so a node dragged into a subtree a recipient can now read arrives with a shell it can materialize, plus the content authored while the node was private; derived from `main` on a branch stream, the shells describe a tree the recipient is not being served. Three readings, none of them benign: a node the branch holds and `main` has dropped gets **no** shell, so the recipient receives a readable `XmlMove` onto a node it cannot materialize — the exact strand the rule exists to prevent; a node `main` holds and the branch does not yields a shell for a node the branch's stream never places; and the back-fill replays *`main`'s* log records for the node's subtree, so a branch reader is handed content from a history its stream does not contain, which is a cross-stream leak rather than a materialization gap. The catch-up `Catchup::Ops` arm calls the same pair with the same argument. Unreached by C60's suite because reveal only fires for `XmlMove`, and a branch stream carrying a tree-move is the shape the residue needs. The fix is the same seam C60 built — resolve both against `Hub::stream_doc(room, branch)` — but the back-fill additionally needs the *branch's* records rather than `main`'s log, so it is a derivation change and not a re-pointing. `element_types` reads `main` on the same loop too and is deliberately **not** part of this: it narrows a type-scoped migration rewrite, not a read verdict. → *Server / Branches*.\n@@ -453,7 +457,7 @@ scalar / counter / register / element / map (#22–#27), list Fugue (#24), text\n \n **C87 — `rename_branch` moves a branch's pointer and leaves its tail and owned base under the retired name (crates/server) — READY, no dependencies. Found during C60 (#386) by a review pass, identified by inspection; pre-existing on `main`.** `Hub::rename_branch` calls `mutate_branches(registry.rename(from, to))` and nothing else. `branch_logs` and `branch_bases` are keyed by branch *name*, and no rename site touches either — the only mutators are `install_room`, `delete_branch`, `repoint_published` and `ingest_branch`. So a renamed branch loses its divergent tail and, for a snapshot fork, its owned base: the new name catches up as a bare live-log fork over `main`'s log, silently dropping every op the branch diverged by, and a published branch renamed becomes a live-log fork of `main` rather than a frozen snapshot. The orphans stay on disk and in memory under the old name, where `delete_branch` can no longer reach them, so a later fork reusing the retired name inherits them — the very shape `delete_branch`'s own cleanup comment says must not happen (\"so a later fork reusing the name never inherits stale ops\"). Wants the rename to carry both maps and both store files with the pointer, under the same persist-before-commit discipline the other mutations take. C60 made it a redaction input as well as a serve one — the tree a branch read is redacted against is folded from exactly those two maps — which is why it is filed rather than left implicit. → *Server / Branches*.\n \n-**C88 — compaction destroys a live-log fork's shared base, and the branch then serves a document with no history (crates/server) — READY, no dependencies. Found during C60 (#386) by a review pass, reproduced.** A live-log fork owns nothing: `catch_up_branch` reads its base straight out of `main`'s **retained** log, in `(last_seen, fork_point.min(head)]`, guarded by `base_end > r.base_seq`. `Hub::compact` folds that log into the replica and lifts `base_seq` to the head, so the guard fails and the branch's catch-up returns its divergent tail alone — a stream whose base has silently evaporated. A fresh subscriber to it materializes an empty-then-tail document, diverging from every peer that joined before the compaction, and then edits from it. Reachable with no operator action wherever `set_compaction_threshold` is configured, since `ingest` compacts inline once the log passes it; `main` itself is unharmed (its replica carries what the log folded into it) and a snapshot fork is unharmed (it owns its base), so this is the live-log fork's alone. **Two escalations a review pass measured on top of that.** The reach is not compaction's alone: `install_room_state` installs a whole replica with an *empty* log at a raised floor, so **every node that took a state transfer** — the ordinary below-floor follower catch-up — clips every live-log fork it holds, with no compaction threshold configured anywhere. And the consequence is not confined to a bad read: `materialize_branch` guards `Catchup::Unavailable` but not this, so a **publish** of a clipped fork freezes the base-less document over the published branch's owned base *and* captures it as a permanent named version. That is irreversible loss of the branch's shared history, not a subscriber that can reconnect. C60 fails *closed* over the redaction half — a clipped shared base yields no tree, so those seams refuse rather than resolve against one that reaches less than the branch holds — and leaves all of the above standing. The fix is to give every live-log fork an owned base **wherever the retained log is dropped below a fork point** — compaction and the snapshot install both: materialize each registered fork whose fork point sits above the new floor into `branch_bases` before the log goes, under the same persist-before-commit rule `fork_branch_from_version` takes, at which point the branch is a snapshot fork and neither seam concerns it again. Note the cost is real and is the ruling to make — one whole-replica copy per live-log fork per room, paid at the compaction that would otherwise reclaim space. → *Server / Branches*.\n+**C88 — compaction destroys a live-log fork's shared base, and the branch then serves a document with no history (crates/server) — READY, no dependencies. Found during C60 (#386) by a review pass, reproduced.** A live-log fork owns nothing: `catch_up_branch` reads its base straight out of `main`'s **retained** log, in `(last_seen, fork_point.min(head)]`, guarded by `base_end > r.base_seq`. `Hub::compact` folds that log into the replica and lifts `base_seq` to the head, so the guard fails and the branch's catch-up returns its divergent tail alone — a stream whose base has silently evaporated. A fresh subscriber to it materializes an empty-then-tail document, diverging from every peer that joined before the compaction, and then edits from it. Reachable with no operator action wherever `set_compaction_threshold` is configured, since `ingest` compacts inline once the log passes it; `main` itself is unharmed (its replica carries what the log folded into it) and a snapshot fork is unharmed (it owns its base), so this is the live-log fork's alone. **Two escalations a review pass measured on top of that.** The reach is not compaction's alone: `install_room_state` installs a whole replica with an *empty* log at a raised floor, so **every node that took a state transfer** — the ordinary below-floor follower catch-up — clips every live-log fork it holds, with no compaction threshold configured anywhere. The consequence was not confined to a bad read either, and that half is now closed: C60 (#386) made a clipped shared base yield no tree, so every seam reading `Hub::stream_doc` refuses rather than resolving against one that reaches less than the branch holds — the redaction indexes, and with them `materialize_branch`, so a **publish** of a clipped fork freezes nothing and (since C51) a diff of one answers `UnreadableBranch` rather than reporting the branch absent, both pinned in `branch_state_taxonomy`. What stands is the read: `catch_up_branch` still answers `Catchup::Ops` with the divergent tail alone, so a fresh subscriber is still caught up to a base-less document and edits from it, and the branch is now unservable at every *other* seam besides — a refusal is not a repair. The fix is to give every live-log fork an owned base **wherever the retained log is dropped below a fork point** — compaction and the snapshot install both: materialize each registered fork whose fork point sits above the new floor into `branch_bases` before the log goes, under the same persist-before-commit rule `fork_branch_from_version` takes, at which point the branch is a snapshot fork and neither seam concerns it again. Note the cost is real and is the ruling to make — one whole-replica copy per live-log fork per room, paid at the compaction that would otherwise reclaim space. → *Server / Branches*.\n \n **C89 — a fork taken off a branch shares `main`'s log, not the source branch's stream (crates/server) — READY, no dependencies. Found during C60 (#386) by a review pass, reproduced.** `Hub::fork_branch(room, new, from, at)` clamps `at` to the **source's head** and then records `new` as an ordinary live-log fork, whose base `catch_up_branch` reads out of `main`'s log in `(floor, fork_point.min(main.head())]`. A branch head counts its divergent tail, so forking off a branch that has diverged produces a `new` whose fork point names a sequence in the *source's* space and whose base is drawn from `main`'s — two different histories under one number. Two readings, both wrong. The branch never inherits the source's divergence: `b1` writes ten ops, `b2` forks off `b1`, and `b2`'s stream carries none of them, which is not what forking a branch means anywhere. And the fork point lands **above** `main`'s head, so `min` clamps it to a moving target and `main`'s later writes keep flowing into `b2`'s base until `main` catches up — a branch that silently absorbs the trunk's history for a while and then stops. C60 made both observable rather than introducing either: the redaction tree is folded from the same derivation, so its shared-base window has to record `main`'s head to stay correct (it does), and a window that grows forces a full refold per `main` write on that branch instead of the tail-forward fold every other branch gets. The fix is that a fork's base is its **source's stream**, not `main`'s: either give the new branch an owned base materialized from the source at the fork point (making it a snapshot fork, which is what `fork_branch_from_version` already does for a version), or teach the catch-up to walk a fork chain. The first is the smaller change and composes with C88, which wants live-log forks to own bases anyway. → *Server / Branches*.\n \n@@ -527,9 +531,7 @@ scalar / counter / register / element / map (#22–#27), list Fugue (#24), text\n **C14 — a redacted op delta leaves the same re-mint hole, and no frame can carry the ids it withholds (crates/server + crates/core) — READY, no dependencies. Found during C9 (#357), reproduced.** C9 closed the *snapshot* seam: a projected snapshot now names the recipient's own ids, so adoption never frees one the room's log holds. An **uncompacted** room serves an op delta instead, and the per-op read filter withholds the recipient's own ops on paths it may no longer read — leaving a hole in its own run with nothing to repair it from. Measured on C9's own fixture: a reader with write at `/` and read on `/a` alone writes into `/b` (seqs 0,1) then `/a` (seq 2); it restarts, its delta withholds `/b`, `next_seq` reports 0, and its next write mints seq 0 straight onto its own withheld id — the write never lands. The state encoding was the carrier for the snapshot case; an `Ops` frame has no equivalent, so closing this needs one: a frontier field on the delta, or a rule that a reader's *own* ops are never withheld from it (which trades the hole for materialising ids in a subtree it may not read — the reason C9 did not simply stop scrubbing). Note the second shape also has to answer what an op carries beyond its id: its target and content may name denied structure. → *Server / Fan-out*.\n \n \n-**C51 — a branch whose durable base this node cannot read is reported as a branch that does not exist (crates/server) — READY, no dependencies. Found during C27 (#375) by review, reasoned not reproduced; filed there as C36 and renumbered here because that id was already taken.** `Hub::materialize_branch` answers `None` for three unrelated situations: a name the branch registry does not hold, a snapshot-forked branch whose persisted base fails to decode (`Catchup::Unavailable`, which `catch_up_branch` returns for exactly the corruption C15's version guard exists for), and `main` on a room this node holds no materialized state for — which is every subscribed-but-never-written room. `Hub::diff_branches` maps all three to `DiffError::UnknownBranch`, so the wire answers `NotFound \"unknown branch draft\"` for a branch `BranchList` will happily enumerate, and `NotFound \"unknown branch main\"` for a room that simply has no ops yet. The publish path reads the same `None` and correctly declines to freeze an empty replica over the branch it names, so the collapse cannot be undone by widening `materialize_branch`'s success case — the three answers have to be told apart, not merged. Fix wants a three-way result (absent / unreadable / empty) with the diff seam mapping unreadable to `DiffError::Decode` and an empty room's `main` to an empty state, and the publish path keeping its refusal on the middle one. A follower reaches the first of those for a different reason: it replicates `main` alone, so a named branch that exists on the leader is simply absent from its registry, and a channel legitimately bound to `main` there is answered `NotFound` for it — the diff seam takes no read redirect. Pre-existing; C27 is what made the seam's error taxonomy load-bearing prose. Distinct from C53, which is the way the same seam answers `Some` with truncated bytes. → *Server / Branches*.\n-\n-**C53 — a log-shared branch materializes truncated once `main` compacts, and says nothing (crates/server) — READY, no dependencies. Found during C27 (#375) by review, reasoned not reproduced; filed there as C38 and renumbered here because that id was already taken.** `catch_up_branch`'s shared-base slice is `r.log[last_seen_seq.max(r.base_seq) - r.base_seq .. fork_point.min(r.head()) - r.base_seq]` — the *retained* log, which begins at `base_seq + 1`. Every op at or below the compaction floor is therefore absent from it, and `materialize_branch` folds what it gets into a **fresh** `Document`, so a branch forked at 10 in a room compacted to 5 materializes from seqs 6..10 alone; with `base_seq >= fork_point` it materializes from its divergent tail alone. Nothing signals it: the answer is `Some(bytes)`, not `Catchup::Unavailable`, and `compact` advances the floor with no guard tying it to any live fork point. Two consequences past the diff (where it makes a branch diff report pre-floor content as an add, wrong but not a leak — `narrow` still runs on both sides): a fresh subscriber to such a branch is caught up to a state missing that content, and `publish`, which materializes the room's *active* branch, freezes the truncated state over the published branch's base *and* into a captured version — silent data loss, reachable once a restore-as-branch has made a log-shared branch the active HEAD (a `main` HEAD materializes through `export_room`, the live replica, and a snapshot-forked branch owns its base, so neither truncates). Fix wants the shared-base catch-up to answer `Catchup::Unavailable` when the base it must serve is no longer retained, and/or a compaction floor that will not advance past a live fork point. Distinct from C51, which is about the three ways the same seam answers `None`; this is the way it answers `Some` with the wrong bytes. → *Server / Branches*.\n+**C53 — a log-shared branch materializes truncated once `main` compacts, and says nothing (crates/server) — READY, no dependencies. Found during C27 (#375) by review, reasoned not reproduced; filed there as C38 and renumbered here because that id was already taken.** `catch_up_branch`'s shared-base slice is `r.log[last_seen_seq.max(r.base_seq) - r.base_seq .. fork_point.min(r.head()) - r.base_seq]` — the *retained* log, which begins at `base_seq + 1`. Every op at or below the compaction floor is therefore absent from it, and `materialize_branch` folds what it gets into a **fresh** `Document`, so a branch forked at 10 in a room compacted to 5 materializes from seqs 6..10 alone; with `base_seq >= fork_point` it materializes from its divergent tail alone. Nothing signals it: the answer is `Some(bytes)`, not `Catchup::Unavailable`, and `compact` advances the floor with no guard tying it to any live fork point. Two consequences past the diff (where it makes a branch diff report pre-floor content as an add, wrong but not a leak — `narrow` still runs on both sides): a fresh subscriber to such a branch is caught up to a state missing that content, and `publish`, which materializes the room's *active* branch, freezes the truncated state over the published branch's base *and* into a captured version — silent data loss, reachable once a restore-as-branch has made a log-shared branch the active HEAD (a `main` HEAD materializes through `export_room`, the live replica, and a snapshot-forked branch owns its base, so neither truncates). Fix wants the shared-base catch-up to answer `Catchup::Unavailable` when the base it must serve is no longer retained, and/or a compaction floor that will not advance past a live fork point. **A fourth route reaches the same wrong `Some`, found during C51:** a snapshot fork's registry entry outliving its base — a base file lost where the branch record was not — leaves `owns_base` false, so `stream_doc` degrades the fork to a *live-log* one and folds `main`'s log under the branch's name. Same signature as the truncation: `Some`, wrong bytes, no signal, and `publish` will freeze them. **Two conditions bound its reach**, and knowing both is what tells whoever implements this how much of it is left: the room's floor must be 0, since above it C51's route through `stream_doc` answers `Unreadable` instead; and the lost base must not have *been* `main`'s own prefix at the fork point, which the ordinary `fork_branch_from_version` off a `main`-captured version reproduces. What is genuinely wrong is an uncompacted room whose lost base was a `published` one, or a version captured off a restored branch — where the fork point lives in the branch's sequence space and `main`'s log at those numbers is other content entirely. Distinct from C51, which is about the ways the same seam answers no state at all; this is the way it answers `Some` with the wrong bytes. → *Server / Branches*.\n \n **C54 — a replicated room's op-version high-water is never carried, so the handshake range-check is inert on every replica (crates/server) — READY, no dependencies. Found during C29 (#374), the sibling field of the same gap; filed as C34, renumbered because that id was taken.** `Room::max_op_version` is the worst-case governing-app op version a joiner must be able to down-reach; `subscriber_reaches_governing` refuses an under-versioned joiner with `onUpdateRequired` against it. It is raised only by the `write_version` argument to `Hub::ingest`, and neither replication path supplies one: `apply_replicate` ingests the leader's batch relay-style (`None`, since the frame carries no version), and `install_snapshot` installs `Document` bytes that carry none either. So a node holding a room only through replication reports `None` for it and the range-check has nothing to enforce — a follower read admits a joiner that cannot decode the room's ops, and so does every read on a promoted leader after a failover, which then down-translates across edges it never checked were invertible. **C29 deliberately went half-way and no further:** it made the *creator* replicated metadata, and preserved the standing high-water across a state-transfer *replace* (so a re-converged follower does not lose one it already had), because the install now writes the metadata record that holds it — but nothing gives a brand-new replica one in the first place. Fix wants the high-water on the same two frames the creator now rides, and the ops path to ingest at the version the leader recorded rather than relay-style `None`; the second half is the larger question, since it decides whether a follower's log is a verbatim mirror of the leader's or a re-tagged one. → *Server / Replication*.\n ", "status": "modified"}, {"additions": 123, "deletions": 36, "filename": "crates/server/src/lib.rs", "patch": "@@ -86,14 +86,26 @@ pub const MAIN_BRANCH: &[u8] = b\"main\";\n pub const PUBLISHED_BRANCH: &[u8] = b\"published\";\n \n /// Why a snapshot diff could not be computed. A diff runs the core engine over\n-/// two decoded whole-replica states; either a named version or branch is absent,\n-/// or a snapshot's encoded state does not decode into a document.\n+/// two decoded whole-replica states; a named version or branch is absent, a branch\n+/// this node holds is one whose state it cannot read, or a snapshot's encoded state\n+/// does not decode into a document.\n+///\n+/// Absence and unreadability are separate answers because they are separate\n+/// situations for the client (C51): a name the room does not have is the client's to\n+/// correct, while a branch the room enumerates and this node cannot state is a\n+/// server-side fault no request the client can phrase gets past.\n #[derive(Debug, Clone, PartialEq, Eq)]\n pub enum DiffError {\n /// A named version the room does not have.\n UnknownVersion(Vec),\n /// A branch the room does not have.\n UnknownBranch(Vec),\n+ /// A branch the room has, whose state this node cannot read: a durable snapshot\n+ /// base that no longer decodes, or a live-log fork whose shared base `main`'s\n+ /// retained log no longer covers. The second needs no damage — a compaction, or a\n+ /// state transfer installing a replica at a raised floor, reaches it in ordinary\n+ /// operation, and the defect under it is C88's.\n+ UnreadableBranch(Vec),\n /// A snapshot's encoded state failed to decode into a document.\n Decode,\n }\n@@ -107,13 +119,36 @@ impl std::fmt::Display for DiffError {\n DiffError::UnknownBranch(name) => {\n write!(f, \"unknown branch {}\", String::from_utf8_lossy(name))\n }\n+ DiffError::UnreadableBranch(name) => write!(\n+ f,\n+ \"branch {} has no state this node can read\",\n+ String::from_utf8_lossy(name)\n+ ),\n DiffError::Decode => write!(f, \"a snapshot's state failed to decode\"),\n }\n }\n }\n \n impl std::error::Error for DiffError {}\n \n+/// What a `(room, branch)` stream materializes to — the answer\n+/// [`Hub::materialize_branch`] hands its callers. The three non-states are three\n+/// different facts about the stream, and the callers are told them apart (C51).\n+enum BranchState {\n+ /// The stream's whole-replica state, encoded.\n+ State(Vec),\n+ /// `main` on a room this node holds no replica for: locally that stream folds to\n+ /// the empty document. Distinct from a stream this node cannot read — nothing\n+ /// here failed to fold.\n+ Empty,\n+ /// A branch the room's registry does not hold.\n+ Absent,\n+ /// A branch the room's registry holds, whose base this node cannot read — a\n+ /// damaged owned base, or a shared base `main`'s retained log no longer covers,\n+ /// which needs no damage at all.\n+ Unreadable,\n+}\n+\n /// Decode two encoded whole-replica states and diff them with the core engine. A\n /// state that does not decode is [`DiffError::Decode`]; identical states diff to\n /// an empty change list.\n@@ -1790,11 +1825,14 @@ impl Hub {\n \n /// The document the `(room, branch)` **stream** serves — `main`'s live replica, or\n /// a named branch's own tree: its shared or owned base with its divergent tail\n- /// folded in. `None` when the stream has no tree to serve: an unknown room or\n- /// branch, or a branch whose owned base does not decode. A caller that redacts owes\n- /// that `None` a refusal — the two indexes it could reach for instead resolve *less*\n- /// than the truth, and a scope or an op target that resolves to nothing is admitted,\n- /// not withheld.\n+ /// folded in. `None` when the stream has no tree to serve: `main` on a room this\n+ /// node holds no replica for, a branch the room's registry does not hold, a branch\n+ /// whose owned base does not decode, or a live-log fork whose shared base `main`'s\n+ /// floor has passed (C88). A caller that redacts owes that `None` a refusal — the two\n+ /// indexes it could reach for instead resolve *less* than the truth, and a scope or\n+ /// an op target that resolves to nothing is admitted, not withheld. A caller that\n+ /// needs those cases apart resolves the name first, as\n+ /// [`materialize_branch`](Hub::materialize_branch) does (C51).\n ///\n /// Every redaction decision is made against the state being served (C28), and on a\n /// branch that state is **not** `main`: a branch owns its base — a captured version,\n@@ -2526,27 +2564,33 @@ impl Hub {\n /// each branch materialized (shared base plus divergent tail, or its owned\n /// snapshot base), narrowed by `narrow`, then fed to the core engine, so a\n /// branch against its fork source yields only the divergence. Diffing a branch\n- /// against itself is empty. A branch that does not materialize is\n- /// [`DiffError::UnknownBranch`] — which today covers more than an unknown name,\n- /// since [`materialize_branch`](Hub::materialize_branch) also answers `None` for a\n- /// branch whose durable base this node cannot read, and for `main` on a room it\n- /// holds no state for (C51), or a live-log fork whose shared base `main`'s\n- /// compaction has dropped (C88). A *materialized* state that does not decode is\n- /// [`DiffError::Decode`]. `narrow` is the reader's redaction, as in\n- /// [`Hub::diff_versions`].\n+ /// against itself is empty.\n+ ///\n+ /// A name the room's registry does not hold is [`DiffError::UnknownBranch`]; a\n+ /// branch it *does* hold whose base this node cannot read is\n+ /// [`DiffError::UnreadableBranch`] — a durable base that no longer decodes (C15),\n+ /// or a live-log fork whose shared base `main`'s compaction has dropped (C88).\n+ /// `main` on a room this node holds no replica for diffs as the empty state this\n+ /// node holds for it, rather than as a missing branch (C51). A *materialized*\n+ /// state that does not decode is [`DiffError::Decode`]. `narrow` is the reader's\n+ /// redaction, as in [`Hub::diff_versions`].\n+ ///\n+ /// Every answer here is about the state *this node* holds, since the read takes no\n+ /// leader redirect: on a follower — which replicates `main` alone — a branch the\n+ /// leader holds is absent, and on a node holding no replica for a room at all,\n+ /// `main` is empty. A channel only binds where this node serves the read itself,\n+ /// which is the room's leader, promoted or not — and there the live stream is\n+ /// served empty too, so the change list stays the diff of two states this reader\n+ /// would itself have been handed. What is missing is the routing, which is C99's.\n pub fn diff_branches(\n &mut self,\n room: &[u8],\n a: &[u8],\n b: &[u8],\n narrow: impl Fn(Vec) -> Vec,\n ) -> Result, DiffError> {\n- let old = self\n- .materialize_branch(room, a)\n- .ok_or_else(|| DiffError::UnknownBranch(a.to_vec()))?;\n- let new = self\n- .materialize_branch(room, b)\n- .ok_or_else(|| DiffError::UnknownBranch(b.to_vec()))?;\n+ let old = self.diff_side(room, a)?;\n+ let new = self.diff_side(room, b)?;\n diff_states(&narrow(old), &narrow(new))\n }\n \n@@ -2883,7 +2927,12 @@ impl Hub {\n if source == published {\n return Ok(false);\n }\n- let Some(state) = self.materialize_branch(room, &source) else {\n+ // Only a materialized state is publishable. An unreadable source would freeze\n+ // an empty replica over the target's base and into a permanent capture, and a\n+ // `main` this node holds no replica for stands for a room it cannot speak for.\n+ // The diff seam tells those two apart, since it can report the second honestly\n+ // (C51); a publish, which writes, can do nothing with either.\n+ let BranchState::State(state) = self.materialize_branch(room, &source) else {\n return Ok(false);\n };\n // The editor sequence being published — the source branch's head — names the\n@@ -2982,27 +3031,65 @@ impl Hub {\n /// The whole-replica state of `(room, branch)` — the bytes a publish freezes\n /// onto the published branch. `main` is the room's live replica; a named branch\n /// folds its own stream (shared base plus divergent tail, or its owned snapshot\n- /// base) into one state. `None` for an unknown room or branch.\n+ /// base) into one state.\n ///\n /// The fold is [`fold_stream`](Hub::fold_stream)'s, the one the redaction index also\n /// walks — what a publish freezes and what a read is narrowed by are the same stream,\n- /// and there is one statement of what that stream is. `None` for an unservable one:\n- /// folding it into a fresh document would materialize an *empty* replica, and the\n- /// publish path writes what it is handed straight over the target branch's base and\n- /// its captured version, so answering `None` is what keeps a stream this node cannot\n- /// read from destroying the branch it names.\n- fn materialize_branch(&mut self, room: &[u8], branch: &[u8]) -> Option> {\n+ /// and there is one statement of what that stream is.\n+ ///\n+ /// Three ways there are no materialized bytes, and they are three different facts\n+ /// about the stream rather than one (C51), so the callers are told them apart:\n+ /// [`Absent`](BranchState::Absent) is a name the room's registry does not hold,\n+ /// [`Unreadable`](BranchState::Unreadable) a branch it does hold whose base this\n+ /// node cannot read, and [`Empty`](BranchState::Empty) `main` on a room this node\n+ /// holds no replica for — every subscribed-but-never-written room, and a stream\n+ /// that folds rather than one that fails to.\n+ ///\n+ /// Only [`State`](BranchState::State) is publishable. Folding an unreadable stream\n+ /// into a fresh document would materialize an *empty* replica, and the publish path\n+ /// writes what it is handed straight over the target branch's base and its captured\n+ /// version, so a clipped shared base would freeze the loss instead of exposing it\n+ /// (C88). Refusing is recoverable; the capture is not.\n+ fn materialize_branch(&mut self, room: &[u8], branch: &[u8]) -> BranchState {\n if branch == MAIN_BRANCH {\n- return self.export_room(room);\n+ // `main` is on every room's branch list, held or not, so it is never an\n+ // absent name. With no replica behind it, its stream folds to the empty\n+ // document — which is a state, not a missing one.\n+ return match self.export_room(room) {\n+ Some(state) => BranchState::State(state),\n+ None => BranchState::Empty,\n+ };\n+ }\n+ // A named branch is in the room's registry or nowhere; `main`, the one name the\n+ // observed set synthesizes, is answered above.\n+ if !self\n+ .branches\n+ .get(room)\n+ .is_some_and(|registry| registry.branch(branch).is_some())\n+ {\n+ return BranchState::Absent;\n }\n // The tree the stream serves, which is also the tree its reads are redacted\n // against — one fold, so what a publish freezes and what a read is narrowed by\n- // cannot describe different streams. A stream this node cannot state answers\n- // `None` rather than a substitute: a publish writes what it folds over the target\n- // branch's base *and* captures it as a permanent version, so a clipped shared\n- // base would freeze the loss instead of exposing it (C88). Refusing is\n- // recoverable; the capture is not.\n- self.stream_doc(room, branch).map(Document::encode_state)\n+ // cannot describe different streams. The name resolved above, so a stream with\n+ // no tree is one this node cannot read rather than one that does not exist.\n+ match self.stream_doc(room, branch) {\n+ Some(doc) => BranchState::State(doc.encode_state()),\n+ None => BranchState::Unreadable,\n+ }\n+ }\n+\n+ /// The whole-replica state a diff reads for `(room, branch)`: the materialized\n+ /// state, or the empty document that stands for a `main` this node holds no\n+ /// replica for. A branch with no readable state at all is the [`DiffError`]\n+ /// naming why.\n+ fn diff_side(&mut self, room: &[u8], branch: &[u8]) -> Result, DiffError> {\n+ match self.materialize_branch(room, branch) {\n+ BranchState::State(state) => Ok(state),\n+ BranchState::Empty => Ok(Document::new(self.server).encode_state()),\n+ BranchState::Absent => Err(DiffError::UnknownBranch(branch.to_vec())),\n+ BranchState::Unreadable => Err(DiffError::UnreadableBranch(branch.to_vec())),\n+ }\n }\n \n /// Apply `change` to `room`'s registry, persisting the result before it", "status": "modified"}, {"additions": 14, "deletions": 11, "filename": "crates/server/src/session.rs", "patch": "@@ -1286,12 +1286,13 @@ pub fn step(\n // not read contributes no change at all rather than a redacted one — with the\n // one exception the projections themselves carry, a *container* the live walk\n // does not reach, which they still serve (C67).\n- // Served locally from the replicated state, so no leader redirect. A version\n- // or branch that does not materialize answers `NotFound`, and a materialized\n- // side that fails to decode `Internal`;\n- // neither closes. A side is archived or reconstructed state — a version's\n+ // Served locally from the replicated state, so no leader redirect — which is\n+ // also what makes every answer a statement about this node's own state (C99).\n+ // A name the room does not have answers `NotFound`; a branch this node cannot\n+ // read, and a materialized side that fails to decode, answer `Internal`. None\n+ // of them closes. A side is archived or reconstructed state — a version's\n // captured bytes, a branch's folded stream, the live replica for `main` — and\n- // one of them failing to decode is a server-side fault this channel's live\n+ // one of them being unreadable is a server-side fault this channel's live\n // stream survives, which is the reading the version fetch already takes.\n Message::DiffQuery {\n channel,\n@@ -2341,18 +2342,20 @@ fn request_denied(session: &Session, what: &str) -> Response {\n }\n }\n \n-/// Map a [`DiffError`] to the client failure it surfaces. A version or branch that\n-/// does not materialize is a recoverable `NotFound` — usually a name the room does\n-/// not have, though a branch whose durable base this node cannot read reaches it too\n-/// (C51). A materialized state that fails to decode is an `Internal` fault, since\n-/// nothing the client sent caused it. Neither closes: a diff's sides are archived or\n+/// Map a [`DiffError`] to the client failure it surfaces. A version or branch the\n+/// room does not have is a recoverable `NotFound` — a name the client can correct.\n+/// A branch the room *does* have whose state this node cannot read is an `Internal`\n+/// fault, as is a materialized state that fails to decode: nothing the client sent\n+/// caused either, and a branch `BranchList` enumerates is not a name the client can\n+/// correct (C51) — the code the subscribe seam gives a branch stream it cannot\n+/// resolve a redaction index for. None of them closes: a diff's sides are archived or\n /// reconstructed state, so one of them being unreadable is a server-side fault the\n /// channel's live stream survives — the reading the version fetch takes of the\n /// version bytes, generalized.\n fn diff_error(e: DiffError) -> Response {\n let code = match e {\n DiffError::UnknownVersion(_) | DiffError::UnknownBranch(_) => ErrorCode::NotFound,\n- DiffError::Decode => ErrorCode::Internal,\n+ DiffError::UnreadableBranch(_) | DiffError::Decode => ErrorCode::Internal,\n };\n Response {\n replies: vec![Message::Error {", "status": "modified"}, {"additions": 386, "deletions": 0, "filename": "crates/server/tests/branch_state_taxonomy.rs", "patch": "@@ -0,0 +1,386 @@\n+//! The three unrelated things a branch can fail to materialize as, told apart (C51).\n+//!\n+//! `Hub::materialize_branch` folds the tree a `(room, branch)` stream serves into a\n+//! whole-replica state. Three situations answer no state, and they are not the same\n+//! situation: the room's registry does not hold the name; the branch is enumerable\n+//! but this node cannot read the base it names — a durable snapshot base that no\n+//! longer decodes, or a live-log fork whose shared base `main`'s retained log no\n+//! longer covers; and `main` on a room this node holds no replica for, which is every\n+//! subscribed-but-never-written room.\n+//!\n+//! The diff seam collapsed all three into `DiffError::UnknownBranch`, so the wire\n+//! answered `NotFound \"unknown branch draft\"` for a branch `BranchList` enumerates,\n+//! and `NotFound \"unknown branch main\"` for a room that simply has no ops yet. They\n+//! are answered apart now: absent is the `NotFound` it always was, unreadable is an\n+//! `Internal` fault naming the branch, and an empty room's `main` diffs as the empty\n+//! state it is.\n+//!\n+//! The publish path reads the same seam and takes none of the three — it writes what\n+//! it folds over the target branch's base *and* captures it as a permanent version,\n+//! so a stream this node cannot state must freeze nothing. That is the constraint\n+//! that made the three have to be told apart rather than merged, and it is pinned\n+//! here beside them. `unreadable_branch_base` pins the same refusal against the\n+//! durable path end to end.\n+\n+use crdtsync_core::diff::decode_changes;\n+use crdtsync_core::protocol::{Channel, DiffKind};\n+use crdtsync_core::{ClientId, Document, ErrorCode, Message, Op, Scalar};\n+use crdtsync_server::store::{Branch, RoomLog, Snapshot, Store};\n+use crdtsync_server::{Catchup, ConnId, DiffError, Hub, Registry};\n+use std::fs;\n+\n+fn cid(first: u8) -> ClientId {\n+ let mut b = [0u8; 16];\n+ b[0] = first;\n+ ClientId::from_bytes(b)\n+}\n+\n+const ROOM: &[u8] = b\"room-t\";\n+const SERVER: u8 = 0xFF;\n+const MAIN: &[u8] = b\"main\";\n+const DRAFT: &[u8] = b\"draft\";\n+const PUBLISHED: &[u8] = b\"published\";\n+const CH: Channel = Channel(0);\n+\n+fn reg(d: &mut Document, key: &[u8], value: i64) -> Vec {\n+ d.transact(|tx| tx.register(key, Scalar::Int(value)))\n+}\n+\n+/// Hello + Auth + Subscribe, holding `ROOM` on `CH`. The subscribe is what binds the\n+/// channel a diff query is keyed by; it does not itself write the room.\n+fn joined(r: &mut Registry, client: u8) -> ConnId {\n+ let id = r.connect();\n+ assert!(r.deliver(\n+ id,\n+ Message::Hello {\n+ client: cid(client),\n+ app_id: Vec::new(),\n+ schema_version: 0,\n+ codecs: Vec::new(),\n+ }\n+ ));\n+ assert!(r.deliver(\n+ id,\n+ Message::Auth {\n+ credential: b\"actor\".to_vec(),\n+ }\n+ ));\n+ assert!(r.deliver(\n+ id,\n+ Message::Subscribe {\n+ channel: CH,\n+ room: ROOM.to_vec(),\n+ last_seen_seq: 0,\n+ branch: Vec::new(),\n+ zone: Vec::new(),\n+ }\n+ ));\n+ r.take_outbox(id);\n+ id\n+}\n+\n+/// A branch diff on `CH`, asserting the query left the connection open — every answer\n+/// in this taxonomy is recoverable, whichever code it carries.\n+fn diff(r: &mut Registry, id: ConnId, a: &[u8], b: &[u8]) -> Vec {\n+ assert!(\n+ r.deliver(\n+ id,\n+ Message::DiffQuery {\n+ channel: CH,\n+ kind: DiffKind::Branches,\n+ a: a.to_vec(),\n+ b: b.to_vec(),\n+ }\n+ ),\n+ \"a diff answer closed the connection\"\n+ );\n+ r.take_outbox(id)\n+}\n+\n+/// The error code of a single-reply outbox, or a panic if it carries no error.\n+fn error_code(out: &[Message]) -> ErrorCode {\n+ match &out[0] {\n+ Message::Error { code, .. } => *code,\n+ other => panic!(\"expected an error, got {other:?}\"),\n+ }\n+}\n+\n+// --- absent: a name the room's registry does not hold ---\n+\n+#[test]\n+fn a_branch_the_room_does_not_hold_is_a_not_found() {\n+ let mut r = Registry::new(cid(SERVER));\n+ let id = joined(&mut r, 1);\n+ let mut author = Document::new(cid(1));\n+ assert!(r.deliver(\n+ id,\n+ Message::Ops {\n+ channel: CH,\n+ ops: reg(&mut author, b\"key\", 1)\n+ }\n+ ));\n+ r.take_outbox(id);\n+\n+ let out = diff(&mut r, id, MAIN, b\"ghost\");\n+ assert_eq!(\n+ error_code(&out),\n+ ErrorCode::NotFound,\n+ \"an absent branch is the recoverable not-found it always was\"\n+ );\n+}\n+\n+// --- empty: `main` on a room this node holds no replica for ---\n+\n+#[test]\n+fn an_empty_room_diffs_main_as_the_empty_state() {\n+ // Subscribed, never written: the channel is bound and the hub holds no room.\n+ let mut r = Registry::new(cid(SERVER));\n+ let id = joined(&mut r, 1);\n+ assert!(\n+ r.hub().export_room(ROOM).is_none(),\n+ \"a subscribe alone does not materialize the room\"\n+ );\n+ assert!(\n+ r.hub().branches(ROOM).iter().any(|b| b.name == MAIN),\n+ \"`main` is enumerable on every room\"\n+ );\n+\n+ let out = diff(&mut r, id, MAIN, MAIN);\n+ match &out[0] {\n+ Message::DiffResult { changes, .. } => assert!(\n+ decode_changes(changes).expect(\"decodes\").is_empty(),\n+ \"a room with no ops has no changes between two reads of `main`\"\n+ ),\n+ other => panic!(\"a room with no ops answered `main` unknown: {other:?}\"),\n+ }\n+}\n+\n+#[test]\n+fn an_empty_room_diffs_main_against_a_written_branch() {\n+ // The asymmetric shape: one side has no replica behind it, the other does. A\n+ // room can hold a branch with a divergent tail before `main` itself is ingested\n+ // into, so the empty side is not merely the trivial self-diff above.\n+ let mut hub = Hub::new(cid(SERVER));\n+ assert!(hub.fork_branch(ROOM, DRAFT, MAIN, 0).unwrap());\n+ let mut author = Document::new(cid(1));\n+ hub.ingest_branch(ROOM, DRAFT, reg(&mut author, b\"key\", 7), None)\n+ .unwrap();\n+\n+ let changes = hub\n+ .diff_branches(ROOM, MAIN, DRAFT, |s| s)\n+ .expect(\"an empty `main` is a state, not an unknown branch\");\n+ assert_eq!(\n+ changes.len(),\n+ 1,\n+ \"the branch's whole divergence is an add over the empty state: {changes:?}\"\n+ );\n+}\n+\n+// --- unreadable: the branch is enumerable and its base does not decode ---\n+\n+/// A room restored from a hand-built log: `key = 1` in its snapshot, a `draft`\n+/// branch whose owned base is `base`, and a `published` branch holding the snapshot\n+/// state. Mirrors `unreadable_branch_base`'s in-memory fixture, which is how a\n+/// damaged durable base is reached without a filesystem.\n+fn room_from(base: &[u8]) -> Hub {\n+ let mut author = Document::new(cid(1));\n+ let ops = reg(&mut author, b\"key\", 1);\n+ let state = author.encode_state();\n+ let log = RoomLog {\n+ snapshot: Some(Snapshot {\n+ base_seq: ops.len() as u64,\n+ state: state.clone(),\n+ }),\n+ branches: vec![\n+ Branch {\n+ name: MAIN.to_vec(),\n+ fork_point: 0,\n+ head: ops.len() as u64,\n+ published: false,\n+ },\n+ Branch {\n+ name: DRAFT.to_vec(),\n+ fork_point: ops.len() as u64,\n+ head: ops.len() as u64,\n+ published: false,\n+ },\n+ Branch {\n+ name: PUBLISHED.to_vec(),\n+ fork_point: ops.len() as u64,\n+ head: ops.len() as u64,\n+ published: true,\n+ },\n+ ],\n+ branch_bases: vec![(DRAFT.to_vec(), base.to_vec()), (PUBLISHED.to_vec(), state)],\n+ active_branch: Some(DRAFT.to_vec()),\n+ ..RoomLog::default()\n+ };\n+ Hub::from_rooms(cid(SERVER), vec![(ROOM.to_vec(), log)]).unwrap()\n+}\n+\n+#[test]\n+fn an_unreadable_base_is_not_an_absent_branch() {\n+ let mut hub = room_from(b\"not a snapshot\");\n+ assert!(\n+ hub.branch(ROOM, DRAFT).is_some(),\n+ \"the branch the registry enumerates\"\n+ );\n+ assert!(\n+ matches!(hub.catch_up_branch(ROOM, DRAFT, 0), Catchup::Unavailable),\n+ \"the base this node cannot read\"\n+ );\n+\n+ let err = hub\n+ .diff_branches(ROOM, MAIN, DRAFT, |s| s)\n+ .expect_err(\"an unreadable base has no state to diff\");\n+ assert_eq!(\n+ err,\n+ DiffError::UnreadableBranch(DRAFT.to_vec()),\n+ \"a branch that exists was not reported unreadable, by name\"\n+ );\n+}\n+\n+#[test]\n+fn a_shared_base_compaction_has_dropped_is_unreadable_too() {\n+ // The second way a branch the registry holds has no state here, and the one that\n+ // needs no damage: a live-log fork reads `main`'s retained log below its fork\n+ // point, and compacting past that point leaves the stream unfoldable (C88).\n+ let mut hub = Hub::new(cid(SERVER));\n+ let mut author = Document::new(cid(1));\n+ hub.ingest(ROOM, reg(&mut author, b\"key\", 1), None).unwrap();\n+ let fork = hub.seq(ROOM);\n+ assert!(hub.fork_branch(ROOM, DRAFT, MAIN, fork).unwrap());\n+ assert!(\n+ hub.diff_branches(ROOM, MAIN, DRAFT, |s| s).is_ok(),\n+ \"the fork diffs while `main` still retains its base\"\n+ );\n+\n+ hub.compact(ROOM).unwrap();\n+ assert!(\n+ hub.branch(ROOM, DRAFT).is_some(),\n+ \"compaction does not retire the branch\"\n+ );\n+ assert_eq!(\n+ hub.diff_branches(ROOM, MAIN, DRAFT, |s| s),\n+ Err(DiffError::UnreadableBranch(DRAFT.to_vec())),\n+ \"a shared base the floor has passed was reported absent\"\n+ );\n+ // The publish refusal covers this flavour too, so the split does not let a\n+ // base-less fold reach a durable capture.\n+ hub.set_active_branch(ROOM, DRAFT).unwrap();\n+ assert!(\n+ !hub.publish(ROOM, PUBLISHED).unwrap(),\n+ \"a clipped shared base publishes nothing\"\n+ );\n+ assert!(\n+ hub.branch(ROOM, PUBLISHED).is_none(),\n+ \"the published branch was pointed at a base-less fold\"\n+ );\n+}\n+\n+#[test]\n+fn a_publish_takes_neither_of_the_two_answers_a_diff_reports() {\n+ // The constraint that keeps the answers apart rather than merged. A diff reports\n+ // `Unreadable` and `Empty` differently, and a publish takes neither: it writes\n+ // what it folds over the target's base and captures it permanently, so both\n+ // refusals stand exactly where the diff seam's answers diverge.\n+ let mut unreadable = room_from(b\"not a snapshot\");\n+ assert_eq!(\n+ unreadable.diff_branches(ROOM, MAIN, DRAFT, |s| s),\n+ Err(DiffError::UnreadableBranch(DRAFT.to_vec()))\n+ );\n+ // What the split could have broken is the refusal itself; that the refused publish\n+ // leaves the target's own state untouched is `unreadable_branch_base`'s, in memory\n+ // and against the durable base both.\n+ assert!(\n+ !unreadable.publish(ROOM, PUBLISHED).unwrap(),\n+ \"a source whose state cannot be read publishes nothing\"\n+ );\n+\n+ let mut empty = Hub::new(cid(SERVER));\n+ assert!(empty\n+ .diff_branches(ROOM, MAIN, MAIN, |s| s)\n+ .unwrap()\n+ .is_empty());\n+ assert!(\n+ !empty.publish(ROOM, PUBLISHED).unwrap(),\n+ \"a room with no replica publishes nothing\"\n+ );\n+ assert!(\n+ empty.branch(ROOM, PUBLISHED).is_none(),\n+ \"the published branch was never pointed\"\n+ );\n+}\n+\n+// --- the same unreadable case at the wire, off a damaged durable base ---\n+\n+#[test]\n+#[cfg_attr(miri, ignore)] // drives the store on the filesystem\n+fn a_damaged_durable_base_surfaces_as_a_fault_not_an_absence() {\n+ let tmp = tempdir();\n+ {\n+ let mut r = Registry::with_store(cid(SERVER), Store::open(tmp.path()).unwrap()).unwrap();\n+ let id = joined(&mut r, 1);\n+ let mut author = Document::new(cid(1));\n+ assert!(r.deliver(\n+ id,\n+ Message::Ops {\n+ channel: CH,\n+ ops: reg(&mut author, b\"key\", 1)\n+ }\n+ ));\n+ r.take_outbox(id);\n+ assert!(r.hub_mut().create_version(ROOM, b\"v1\").unwrap());\n+ assert!(r\n+ .hub_mut()\n+ .fork_branch_from_version(ROOM, DRAFT, b\"v1\")\n+ .unwrap());\n+ }\n+ // Damage the branch's durable base, then reload from it.\n+ let mut store = Store::open(tmp.path()).unwrap();\n+ store\n+ .write_branch_base(ROOM, DRAFT, b\"not a snapshot\")\n+ .unwrap();\n+ drop(store);\n+\n+ let mut r = Registry::with_store(cid(SERVER), Store::open(tmp.path()).unwrap()).unwrap();\n+ let id = joined(&mut r, 1);\n+ assert!(\n+ r.hub().branches(ROOM).iter().any(|b| b.name == DRAFT),\n+ \"`BranchList` enumerates the branch\"\n+ );\n+\n+ let out = diff(&mut r, id, MAIN, DRAFT);\n+ assert_eq!(\n+ error_code(&out),\n+ ErrorCode::Internal,\n+ \"a base this node cannot read was reported as a branch that does not exist\"\n+ );\n+}\n+\n+// --- a tempdir without pulling in a dev-dependency ---\n+\n+struct TempDir(std::path::PathBuf);\n+\n+impl TempDir {\n+ fn path(&self) -> &std::path::Path {\n+ &self.0\n+ }\n+}\n+\n+impl Drop for TempDir {\n+ fn drop(&mut self) {\n+ let _ = fs::remove_dir_all(&self.0);\n+ }\n+}\n+\n+fn tempdir() -> TempDir {\n+ use std::sync::atomic::{AtomicU32, Ordering};\n+ static COUNTER: AtomicU32 = AtomicU32::new(0);\n+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);\n+ let pid = std::process::id();\n+ let dir = std::env::temp_dir().join(format!(\"crdtsync-branch-taxonomy-{pid}-{n}\"));\n+ let _ = fs::remove_dir_all(&dir);\n+ fs::create_dir_all(&dir).unwrap();\n+ TempDir(dir)\n+}", "status": "added"}, {"additions": 2, "deletions": 1, "filename": "crates/server/tests/diff_query.rs", "patch": "@@ -4,7 +4,8 @@\n //! A client asks for the diff between two of a room's saved versions or two of\n //! its branches; the server routes the query to the matching `Hub::diff_*` seam,\n //! encodes the change list into a `DiffResult`, and maps an absent version/branch\n-//! to a recoverable `NotFound`. The query is channel-keyed: the room, and the scope\n+//! to a recoverable `NotFound` — the other two answers a branch can carry, unreadable\n+//! and empty, are `branch_state_taxonomy`'s. The query is channel-keyed: the room, and the scope\n //! the change list is narrowed to, come from the subscription the channel holds\n //! (`diff_projection` pins the narrowing). Gated by the same read tier a version\n //! request uses — a diff request before auth is a protocol violation, one on an", "status": "modified"}, {"additions": 3, "deletions": 2, "filename": "crates/server/tests/version_unreadable.rs", "patch": "@@ -16,8 +16,9 @@\n //! engine has to decode both sides to compare them, so a diff cannot serve a side it\n //! cannot read whoever asks, where a fetch serves a reader nothing would narrow for.\n //! These two cases are a `DiffKind::Versions` query; a *branch* whose durable base\n-//! does not decode reaches the seam as an unmaterializable branch instead, which is\n-//! answered `NotFound` rather than `Internal` (C51).\n+//! does not decode reaches the seam as an unreadable branch instead, told apart from\n+//! an absent name and answered with the same `Internal` (C51, pinned by\n+//! `branch_state_taxonomy`).\n \n use std::fs;\n use std::path::{Path, PathBuf};", "status": "modified"}], "message": "fix(server): tell a branch this node cannot read from one it does not have (C51)\n\n`Hub::materialize_branch` answered one `None` for three unrelated facts about a\n`(room, branch)` stream — a name the registry does not hold, a branch it holds\nwhose base this node cannot read, and `main` on a room with no replica — and\n`diff_branches` mapped all three to `UnknownBranch`, so the wire reported a\nbranch `BranchList` enumerates as nonexistent, and an unwritten room's `main`\nlikewise.\n\nThe publish path reads the same seam and correctly declines each one, since it\nfreezes what it folds over the target's base and captures it permanently. So the\nseam answers a four-way `BranchState`: the diff maps `Absent` to `UnknownBranch`,\n`Unreadable` to a new `UnreadableBranch(name)` surfacing as `Internal`, and\n`Empty` to the empty document; publish takes `State` alone.\n\nFiles the follower's missing read redirect as C99.", "sha": "5b02b0348700105aa925448d0132b67b1a436016"}, {"author": "vieiralucas", "date": "2026-08-09T00:29:39Z", "files": [{"additions": 1, "deletions": 1, "filename": "KANBAN.md", "patch": "@@ -30,7 +30,7 @@ Element + Map are one coupled unit (Map slots hold Elements; Element forwards li\n \n _Derived from code + git; a convenience view, not the source of truth._\n \n-**C51 — a branch whose durable base this node cannot read is reported as a branch that does not exist (crates/server) — DONE (#PRNUM).** Filed by review during C27 (#375) as reasoned-not-reproduced; **all three cases reproduced first**, each as a failing test before a line of the fix. `Hub::materialize_branch` answered `Option>`, and its `None` stood for three unrelated facts about a stream: a name the room's branch registry does not hold; a branch it *does* hold whose base this node cannot read — a durable snapshot base that no longer decodes, the corruption C15's version guard exists for, or — since C60 (#386), over the defect C88 files — a live-log fork whose shared base `main`'s compaction has dropped; and `main` on a room this node holds no replica for, which is every subscribed-but-never-written room. `Hub::diff_branches` mapped all three to `DiffError::UnknownBranch`, so the wire answered `NotFound \"unknown branch draft\"` for a branch `BranchList` enumerates and `NotFound \"unknown branch main\"` for a room that simply has no ops yet — both measured at the wire, the second off nothing but a `Subscribe`. **The three had to be told apart rather than merged**, which is what made it more than a widened success case: the publish path reads the same seam and *correctly* declines to freeze an empty replica over the branch it names, so admitting the middle case there would trade a wrong error message for silent durable loss. `materialize_branch` now answers a four-way `BranchState` (`State` / `Empty` / `Absent` / `Unreadable`). The diff seam maps `Absent` to the `DiffError::UnknownBranch` it always was, `Unreadable` to a new `DiffError::UnreadableBranch(name)` surfacing as `Internal` — the code the *version* seam already gives an archived side it cannot read, and neither closes the connection — and `Empty` to the empty document an unwritten room's `main` genuinely is, narrowed by the reader's projection like any other side. `publish` takes `State` alone, so both of its refusals stand unchanged, pinned as tests rather than left to the enum. **One deviation from the filing's fix direction, stated:** it proposed mapping unreadable onto `DiffError::Decode`; a named variant was taken instead, because C88's clipped shared base is not a decode failure and the variant names *which* branch is unreadable, while `Decode` keeps meaning what it says — the re-decode inside `diff_states`. **The residue the filing named is filed rather than covered, as C99**: the diff seam takes no read redirect, so on a follower — which replicates `main` alone — a branch the leader holds is genuinely absent locally, and the honest local answer is the misleading one. That needs the read-routing a diff request does not carry, which is the design C33 owns for the version fetch, so it is the same unit's question and not this one's. Spec `crates/server/tests/branch_state_taxonomy.rs` (7): the absent name still `NotFound`, an empty room's `main` both as a self-diff at the wire and against a branch written before `main` ever was, and the unreadable answer in both of its flavours — a genuinely damaged durable base, told from absence at the hub seam and surfacing as `Internal` at the wire, and the flavour that needs no damage at all, a live-log fork whose shared base a routine `compact` has passed, with a control that the same fork diffs fine before the floor moves — plus, on each of the two inputs the diff seam now answers *differently*, the publish refusing both, which is the constraint the split must not break. → *Server / Branches, Diff*.\n+**C51 — a branch whose durable base this node cannot read is reported as a branch that does not exist (crates/server) — DONE (#393).** Filed by review during C27 (#375) as reasoned-not-reproduced; **all three cases reproduced first**, each as a failing test before a line of the fix. `Hub::materialize_branch` answered `Option>`, and its `None` stood for three unrelated facts about a stream: a name the room's branch registry does not hold; a branch it *does* hold whose base this node cannot read — a durable snapshot base that no longer decodes, the corruption C15's version guard exists for, or — since C60 (#386), over the defect C88 files — a live-log fork whose shared base `main`'s compaction has dropped; and `main` on a room this node holds no replica for, which is every subscribed-but-never-written room. `Hub::diff_branches` mapped all three to `DiffError::UnknownBranch`, so the wire answered `NotFound \"unknown branch draft\"` for a branch `BranchList` enumerates and `NotFound \"unknown branch main\"` for a room that simply has no ops yet — both measured at the wire, the second off nothing but a `Subscribe`. **The three had to be told apart rather than merged**, which is what made it more than a widened success case: the publish path reads the same seam and *correctly* declines to freeze an empty replica over the branch it names, so admitting the middle case there would trade a wrong error message for silent durable loss. `materialize_branch` now answers a four-way `BranchState` (`State` / `Empty` / `Absent` / `Unreadable`). The diff seam maps `Absent` to the `DiffError::UnknownBranch` it always was, `Unreadable` to a new `DiffError::UnreadableBranch(name)` surfacing as `Internal` — the code the *version* seam already gives an archived side it cannot read, and neither closes the connection — and `Empty` to the empty document an unwritten room's `main` genuinely is, narrowed by the reader's projection like any other side. `publish` takes `State` alone, so both of its refusals stand unchanged, pinned as tests rather than left to the enum. **One deviation from the filing's fix direction, stated:** it proposed mapping unreadable onto `DiffError::Decode`; a named variant was taken instead, because C88's clipped shared base is not a decode failure and the variant names *which* branch is unreadable, while `Decode` keeps meaning what it says — the re-decode inside `diff_states`. **The residue the filing named is filed rather than covered, as C99**: the diff seam takes no read redirect, so on a follower — which replicates `main` alone — a branch the leader holds is genuinely absent locally, and the honest local answer is the misleading one. That needs the read-routing a diff request does not carry, which is the design C33 owns for the version fetch, so it is the same unit's question and not this one's. Spec `crates/server/tests/branch_state_taxonomy.rs` (7): the absent name still `NotFound`, an empty room's `main` both as a self-diff at the wire and against a branch written before `main` ever was, and the unreadable answer in both of its flavours — a genuinely damaged durable base, told from absence at the hub seam and surfacing as `Internal` at the wire, and the flavour that needs no damage at all, a live-log fork whose shared base a routine `compact` has passed, with a control that the same fork diffs fine before the floor moves — plus, on each of the two inputs the diff seam now answers *differently*, the publish refusing both, which is the constraint the split must not break. → *Server / Branches, Diff*.\n \n **C16 — the reveal back-fill's batch dedup dropped the copy that was zone-protected (crates/server) — DONE (#391).** Filed by cold review during C11 (#359) as reasoned-not-reproduced; **reproduced, and the filing's reachability claim was wrong in the direction that made it look narrower than it is.** The live fan-out's reveal prefix force-stamps every shell and back-filled op with the placing move's zone precisely so a per-channel `zone_filter` cannot drop the content while keeping the shell. C11 made the back-fill skip an op the delivered batch already carries — right, since a second untagged copy takes the batch's tagged one out of its transaction's count — but the surviving copy is then the *batch's*, stamped in the partition its author resolved at emit time. `zone_of_op` resolves a tree op against the live tree, and within one commit an edit inside a node precedes the move that relocates it, so the edit takes the partition the node is moving **out of** while the move takes the destination's: a channel scoped to the destination zone kept the shell, the historical back-fill and the move, and dropped the batch's own edit — a materialised node the reader never finishes filling, diverging permanently from a fresh joiner. **C74 did not close it.** C74 changed how *governing-region* ops (Ranged, ACL) derive their partition; a tree op still takes the partition of the container it targets, resolved against the tree as it stands when the op is emitted, which is the whole mechanism. **Reachability is wider than filed: the shape does not need a named branch.** The filing reasoned that a cross-zone move is only un-gated on a branch (`handle_ops` gates `batch_zone_crossings` on `branch == MAIN_BRANCH`), but Zones-4's capability token admits exactly one crossing on `main`, and the batch riding that token may carry any number of *non*-crossing edits inside the moved node — an edit that moves a node the destination zone already holds into the revealed node crosses nothing, so one token authorizes the whole batch. That is the regression fixture: a card born in `/board` (za, doc-ACL-denied to the reader) carrying a private grandchild, a pin already in `/notes/pub` (zb, readable), one atomic transaction moving the pin into the card and then the card into `/notes/pub`, and a reader scoped to zb who reads `/notes` but not `/notes/priv`. **The first cut re-stamped from the move's envelope and a cold review reproduced a second hole of the same shape, which is why the ruling is not \"stamp the batch copy too\".** A *nested* reveal has two born-denied nodes in one batch, and the move that places the inner one into the outer is emitted while the outer still sits at its origin — so its envelope names the origin partition, and the inner **shell** derived from it was dropped by a destination-scoped channel while the outer's survived. Measured on the same fixture with `x`,`y` born denied inside `/notes/priv` and `card` denied in `/board`: two shells delivered instead of three, `x` never materialised, bob's tree frozen short of the author's. The same derivation also made the dedup's choice of which shell's zone to record depend on `reveal_ops`' element-id sort order, so an op `origin/main` delivered could be withheld. **Ruling: a relocated node's partition is the one it *lands in*, read off the tree the stream serves once the batch is folded — not the one its move's envelope names.** An envelope carries the partition its author resolved when the op was emitted, which is a statement about ordering inside a transaction, not about where the subtree ends up; the folded tree gives every node in one relocated subtree the same answer whatever order the transaction emitted its moves in. So `moved_nodes` resolves each node through the fan-out's own element-path index, and the shell, its back-fill, and the batch's surviving copy of any op the back-fill would have carried all ride that partition. A node the served tree does not resolve keeps its move's answer, the only other partition claim available. The re-stamp is per-recipient (the batch is cloned by `retain_atomic_cloned` before it), so no other recipient's verdict moves; the recipient's per-zone clock advances in the destination partition, which is where the content now lives, and `mint_floor` maxes the partition clock with the replica's own global high-water so a clock left short elsewhere cannot collide. Zone isolation does not move — the re-stamped set is a strict subset of what `reveal_backfill` already yields under the same per-recipient read gate, stamped in the same partition — and the landing partition is resolved under the room's *governing* schema, which is the id space a channel's zone scope was itself resolved in, where an author's envelope only coincidentally is. The `registry.rs` comment claimed more than either derivation supports (that a shell never rides where its placing move is dropped, which is a claim about an op keeping its own envelope) and now states what holds: a revealed node's shell and its contents travel together or not at all. Scope is `main`: `reveal_backfill` reads `main`'s log and document, so on a branch stream the back-fill and the batch never intersect — the branch half is C85's. Spec `crates/server/tests/reveal_zone.rs` (4), pinning the preconditions beside the outcomes — the two ops must carry different partitions, and (since C2 cuts a commit into one atomic transaction per partition) they are two groups, so the co-travel is the only thing keeping them on one channel — plus two controls: a reader no reveal fires for is not re-stamped, and a channel scoped to the partition the node *leaves* is told nothing of it rather than handed content it can never place, which is the fail-closed mirror of the defect and the one behaviour this changes for a reader `origin/main` served. → *Server / Fan-out*.\n ", "status": "modified"}], "message": "docs(kanban): record C51's PR number", "sha": "aca08038b4a9977c09afaf327a38d2101bd9c5e9"}], "post_review_commits": ["6bb9b4450aa62e46ce4086af4823a6f2dc841027", "1a2fb9b0f29a46077592a5ca259df16a40e95093", "0dad283695ad35a38f68ca5fa33585b5fca15d95"], "pr_author": "vieiralucas", "pr_title": "fix(server): tell a branch this node cannot read from one it does not have (C51)", "repo_name": "faiscadev/crdtsync"}, "repo": "faiscadev/crdtsync", "snapshot": "snapshots/11e288aa01d68a455fdbafd9b22e117e0d3a6f87cf0cf903d6b8b74f9a3369a1.pack", "split": "eval", "task_id": "ff03a91fea62bfbcf8fa122081825fce9b31297093c17d4c044e653b206207f3"}