From ef1c743520fbe0e993923703dbaab6d11db87208 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:14 +0200 Subject: [PATCH 01/10] deps: add websockets>=12 for Copilot App IPC Required by the hybrid project-scoping path (PR A). When the App is running, APM prefers the localhost WS-IPC surface so workflow rows fire the live WorkflowsChanged broadcast instead of relying on the webview re-reading SQLite. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyproject.toml | 1 + uv.lock | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 0ba03ddbee..46c683bea2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,7 @@ dependencies = [ "GitPython>=3.1.0", "ruamel.yaml>=0.18.0", "filelock>=3.12", + "websockets>=12", ] [project.optional-dependencies] diff --git a/uv.lock b/uv.lock index 51447060f0..6a9f5e1c42 100644 --- a/uv.lock +++ b/uv.lock @@ -202,6 +202,7 @@ dependencies = [ { name = "toml" }, { name = "tomli", marker = "python_full_version < '3.11'" }, { name = "watchdog" }, + { name = "websockets" }, ] [package.optional-dependencies] @@ -245,6 +246,7 @@ requires-dist = [ { name = "toml", specifier = ">=0.10.2" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=1.2.0" }, { name = "watchdog", specifier = ">=3.0.0" }, + { name = "websockets", specifier = ">=12" }, ] provides-extras = ["dev", "build"] @@ -2006,6 +2008,74 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, ] +[[package]] +name = "websockets" +version = "16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/04/24/4b2031d72e840ce4c1ccb255f693b15c334757fc50023e4db9537080b8c4/websockets-16.0.tar.gz", hash = "sha256:5f6261a5e56e8d5c42a4497b364ea24d94d9563e8fbd44e78ac40879c60179b5", size = 179346, upload-time = "2026-01-10T09:23:47.181Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/74/221f58decd852f4b59cc3354cccaf87e8ef695fede361d03dc9a7396573b/websockets-16.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:04cdd5d2d1dacbad0a7bf36ccbcd3ccd5a30ee188f2560b7a62a30d14107b31a", size = 177343, upload-time = "2026-01-10T09:22:21.28Z" }, + { url = "https://files.pythonhosted.org/packages/19/0f/22ef6107ee52ab7f0b710d55d36f5a5d3ef19e8a205541a6d7ffa7994e5a/websockets-16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:8ff32bb86522a9e5e31439a58addbb0166f0204d64066fb955265c4e214160f0", size = 175021, upload-time = "2026-01-10T09:22:22.696Z" }, + { url = "https://files.pythonhosted.org/packages/10/40/904a4cb30d9b61c0e278899bf36342e9b0208eb3c470324a9ecbaac2a30f/websockets-16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:583b7c42688636f930688d712885cf1531326ee05effd982028212ccc13e5957", size = 175320, upload-time = "2026-01-10T09:22:23.94Z" }, + { url = "https://files.pythonhosted.org/packages/9d/2f/4b3ca7e106bc608744b1cdae041e005e446124bebb037b18799c2d356864/websockets-16.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7d837379b647c0c4c2355c2499723f82f1635fd2c26510e1f587d89bc2199e72", size = 183815, upload-time = "2026-01-10T09:22:25.469Z" }, + { url = "https://files.pythonhosted.org/packages/86/26/d40eaa2a46d4302becec8d15b0fc5e45bdde05191e7628405a19cf491ccd/websockets-16.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:df57afc692e517a85e65b72e165356ed1df12386ecb879ad5693be08fac65dde", size = 185054, upload-time = "2026-01-10T09:22:27.101Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ba/6500a0efc94f7373ee8fefa8c271acdfd4dca8bd49a90d4be7ccabfc397e/websockets-16.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:2b9f1e0d69bc60a4a87349d50c09a037a2607918746f07de04df9e43252c77a3", size = 184565, upload-time = "2026-01-10T09:22:28.293Z" }, + { url = "https://files.pythonhosted.org/packages/04/b4/96bf2cee7c8d8102389374a2616200574f5f01128d1082f44102140344cc/websockets-16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:335c23addf3d5e6a8633f9f8eda77efad001671e80b95c491dd0924587ece0b3", size = 183848, upload-time = "2026-01-10T09:22:30.394Z" }, + { url = "https://files.pythonhosted.org/packages/02/8e/81f40fb00fd125357814e8c3025738fc4ffc3da4b6b4a4472a82ba304b41/websockets-16.0-cp310-cp310-win32.whl", hash = "sha256:37b31c1623c6605e4c00d466c9d633f9b812ea430c11c8a278774a1fde1acfa9", size = 178249, upload-time = "2026-01-10T09:22:32.083Z" }, + { url = "https://files.pythonhosted.org/packages/b4/5f/7e40efe8df57db9b91c88a43690ac66f7b7aa73a11aa6a66b927e44f26fa/websockets-16.0-cp310-cp310-win_amd64.whl", hash = "sha256:8e1dab317b6e77424356e11e99a432b7cb2f3ec8c5ab4dabbcee6add48f72b35", size = 178685, upload-time = "2026-01-10T09:22:33.345Z" }, + { url = "https://files.pythonhosted.org/packages/f2/db/de907251b4ff46ae804ad0409809504153b3f30984daf82a1d84a9875830/websockets-16.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:31a52addea25187bde0797a97d6fc3d2f92b6f72a9370792d65a6e84615ac8a8", size = 177340, upload-time = "2026-01-10T09:22:34.539Z" }, + { url = "https://files.pythonhosted.org/packages/f3/fa/abe89019d8d8815c8781e90d697dec52523fb8ebe308bf11664e8de1877e/websockets-16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:417b28978cdccab24f46400586d128366313e8a96312e4b9362a4af504f3bbad", size = 175022, upload-time = "2026-01-10T09:22:36.332Z" }, + { url = "https://files.pythonhosted.org/packages/58/5d/88ea17ed1ded2079358b40d31d48abe90a73c9e5819dbcde1606e991e2ad/websockets-16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:af80d74d4edfa3cb9ed973a0a5ba2b2a549371f8a741e0800cb07becdd20f23d", size = 175319, upload-time = "2026-01-10T09:22:37.602Z" }, + { url = "https://files.pythonhosted.org/packages/d2/ae/0ee92b33087a33632f37a635e11e1d99d429d3d323329675a6022312aac2/websockets-16.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:08d7af67b64d29823fed316505a89b86705f2b7981c07848fb5e3ea3020c1abe", size = 184631, upload-time = "2026-01-10T09:22:38.789Z" }, + { url = "https://files.pythonhosted.org/packages/c8/c5/27178df583b6c5b31b29f526ba2da5e2f864ecc79c99dae630a85d68c304/websockets-16.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7be95cfb0a4dae143eaed2bcba8ac23f4892d8971311f1b06f3c6b78952ee70b", size = 185870, upload-time = "2026-01-10T09:22:39.893Z" }, + { url = "https://files.pythonhosted.org/packages/87/05/536652aa84ddc1c018dbb7e2c4cbcd0db884580bf8e95aece7593fde526f/websockets-16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d6297ce39ce5c2e6feb13c1a996a2ded3b6832155fcfc920265c76f24c7cceb5", size = 185361, upload-time = "2026-01-10T09:22:41.016Z" }, + { url = "https://files.pythonhosted.org/packages/6d/e2/d5332c90da12b1e01f06fb1b85c50cfc489783076547415bf9f0a659ec19/websockets-16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1c1b30e4f497b0b354057f3467f56244c603a79c0d1dafce1d16c283c25f6e64", size = 184615, upload-time = "2026-01-10T09:22:42.442Z" }, + { url = "https://files.pythonhosted.org/packages/77/fb/d3f9576691cae9253b51555f841bc6600bf0a983a461c79500ace5a5b364/websockets-16.0-cp311-cp311-win32.whl", hash = "sha256:5f451484aeb5cafee1ccf789b1b66f535409d038c56966d6101740c1614b86c6", size = 178246, upload-time = "2026-01-10T09:22:43.654Z" }, + { url = "https://files.pythonhosted.org/packages/54/67/eaff76b3dbaf18dcddabc3b8c1dba50b483761cccff67793897945b37408/websockets-16.0-cp311-cp311-win_amd64.whl", hash = "sha256:8d7f0659570eefb578dacde98e24fb60af35350193e4f56e11190787bee77dac", size = 178684, upload-time = "2026-01-10T09:22:44.941Z" }, + { url = "https://files.pythonhosted.org/packages/84/7b/bac442e6b96c9d25092695578dda82403c77936104b5682307bd4deb1ad4/websockets-16.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:71c989cbf3254fbd5e84d3bff31e4da39c43f884e64f2551d14bb3c186230f00", size = 177365, upload-time = "2026-01-10T09:22:46.787Z" }, + { url = "https://files.pythonhosted.org/packages/b0/fe/136ccece61bd690d9c1f715baaeefd953bb2360134de73519d5df19d29ca/websockets-16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8b6e209ffee39ff1b6d0fa7bfef6de950c60dfb91b8fcead17da4ee539121a79", size = 175038, upload-time = "2026-01-10T09:22:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/40/1e/9771421ac2286eaab95b8575b0cb701ae3663abf8b5e1f64f1fd90d0a673/websockets-16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:86890e837d61574c92a97496d590968b23c2ef0aeb8a9bc9421d174cd378ae39", size = 175328, upload-time = "2026-01-10T09:22:49.809Z" }, + { url = "https://files.pythonhosted.org/packages/18/29/71729b4671f21e1eaa5d6573031ab810ad2936c8175f03f97f3ff164c802/websockets-16.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9b5aca38b67492ef518a8ab76851862488a478602229112c4b0d58d63a7a4d5c", size = 184915, upload-time = "2026-01-10T09:22:51.071Z" }, + { url = "https://files.pythonhosted.org/packages/97/bb/21c36b7dbbafc85d2d480cd65df02a1dc93bf76d97147605a8e27ff9409d/websockets-16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e0334872c0a37b606418ac52f6ab9cfd17317ac26365f7f65e203e2d0d0d359f", size = 186152, upload-time = "2026-01-10T09:22:52.224Z" }, + { url = "https://files.pythonhosted.org/packages/4a/34/9bf8df0c0cf88fa7bfe36678dc7b02970c9a7d5e065a3099292db87b1be2/websockets-16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a0b31e0b424cc6b5a04b8838bbaec1688834b2383256688cf47eb97412531da1", size = 185583, upload-time = "2026-01-10T09:22:53.443Z" }, + { url = "https://files.pythonhosted.org/packages/47/88/4dd516068e1a3d6ab3c7c183288404cd424a9a02d585efbac226cb61ff2d/websockets-16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:485c49116d0af10ac698623c513c1cc01c9446c058a4e61e3bf6c19dff7335a2", size = 184880, upload-time = "2026-01-10T09:22:55.033Z" }, + { url = "https://files.pythonhosted.org/packages/91/d6/7d4553ad4bf1c0421e1ebd4b18de5d9098383b5caa1d937b63df8d04b565/websockets-16.0-cp312-cp312-win32.whl", hash = "sha256:eaded469f5e5b7294e2bdca0ab06becb6756ea86894a47806456089298813c89", size = 178261, upload-time = "2026-01-10T09:22:56.251Z" }, + { url = "https://files.pythonhosted.org/packages/c3/f0/f3a17365441ed1c27f850a80b2bc680a0fa9505d733fe152fdf5e98c1c0b/websockets-16.0-cp312-cp312-win_amd64.whl", hash = "sha256:5569417dc80977fc8c2d43a86f78e0a5a22fee17565d78621b6bb264a115d4ea", size = 178693, upload-time = "2026-01-10T09:22:57.478Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9c/baa8456050d1c1b08dd0ec7346026668cbc6f145ab4e314d707bb845bf0d/websockets-16.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:878b336ac47938b474c8f982ac2f7266a540adc3fa4ad74ae96fea9823a02cc9", size = 177364, upload-time = "2026-01-10T09:22:59.333Z" }, + { url = "https://files.pythonhosted.org/packages/7e/0c/8811fc53e9bcff68fe7de2bcbe75116a8d959ac699a3200f4847a8925210/websockets-16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:52a0fec0e6c8d9a784c2c78276a48a2bdf099e4ccc2a4cad53b27718dbfd0230", size = 175039, upload-time = "2026-01-10T09:23:01.171Z" }, + { url = "https://files.pythonhosted.org/packages/aa/82/39a5f910cb99ec0b59e482971238c845af9220d3ab9fa76dd9162cda9d62/websockets-16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e6578ed5b6981005df1860a56e3617f14a6c307e6a71b4fff8c48fdc50f3ed2c", size = 175323, upload-time = "2026-01-10T09:23:02.341Z" }, + { url = "https://files.pythonhosted.org/packages/bd/28/0a25ee5342eb5d5f297d992a77e56892ecb65e7854c7898fb7d35e9b33bd/websockets-16.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:95724e638f0f9c350bb1c2b0a7ad0e83d9cc0c9259f3ea94e40d7b02a2179ae5", size = 184975, upload-time = "2026-01-10T09:23:03.756Z" }, + { url = "https://files.pythonhosted.org/packages/f9/66/27ea52741752f5107c2e41fda05e8395a682a1e11c4e592a809a90c6a506/websockets-16.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c0204dc62a89dc9d50d682412c10b3542d748260d743500a85c13cd1ee4bde82", size = 186203, upload-time = "2026-01-10T09:23:05.01Z" }, + { url = "https://files.pythonhosted.org/packages/37/e5/8e32857371406a757816a2b471939d51c463509be73fa538216ea52b792a/websockets-16.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:52ac480f44d32970d66763115edea932f1c5b1312de36df06d6b219f6741eed8", size = 185653, upload-time = "2026-01-10T09:23:06.301Z" }, + { url = "https://files.pythonhosted.org/packages/9b/67/f926bac29882894669368dc73f4da900fcdf47955d0a0185d60103df5737/websockets-16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6e5a82b677f8f6f59e8dfc34ec06ca6b5b48bc4fcda346acd093694cc2c24d8f", size = 184920, upload-time = "2026-01-10T09:23:07.492Z" }, + { url = "https://files.pythonhosted.org/packages/3c/a1/3d6ccdcd125b0a42a311bcd15a7f705d688f73b2a22d8cf1c0875d35d34a/websockets-16.0-cp313-cp313-win32.whl", hash = "sha256:abf050a199613f64c886ea10f38b47770a65154dc37181bfaff70c160f45315a", size = 178255, upload-time = "2026-01-10T09:23:09.245Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ae/90366304d7c2ce80f9b826096a9e9048b4bb760e44d3b873bb272cba696b/websockets-16.0-cp313-cp313-win_amd64.whl", hash = "sha256:3425ac5cf448801335d6fdc7ae1eb22072055417a96cc6b31b3861f455fbc156", size = 178689, upload-time = "2026-01-10T09:23:10.483Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1d/e88022630271f5bd349ed82417136281931e558d628dd52c4d8621b4a0b2/websockets-16.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8cc451a50f2aee53042ac52d2d053d08bf89bcb31ae799cb4487587661c038a0", size = 177406, upload-time = "2026-01-10T09:23:12.178Z" }, + { url = "https://files.pythonhosted.org/packages/f2/78/e63be1bf0724eeb4616efb1ae1c9044f7c3953b7957799abb5915bffd38e/websockets-16.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:daa3b6ff70a9241cf6c7fc9e949d41232d9d7d26fd3522b1ad2b4d62487e9904", size = 175085, upload-time = "2026-01-10T09:23:13.511Z" }, + { url = "https://files.pythonhosted.org/packages/bb/f4/d3c9220d818ee955ae390cf319a7c7a467beceb24f05ee7aaaa2414345ba/websockets-16.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fd3cb4adb94a2a6e2b7c0d8d05cb94e6f1c81a0cf9dc2694fb65c7e8d94c42e4", size = 175328, upload-time = "2026-01-10T09:23:14.727Z" }, + { url = "https://files.pythonhosted.org/packages/63/bc/d3e208028de777087e6fb2b122051a6ff7bbcca0d6df9d9c2bf1dd869ae9/websockets-16.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:781caf5e8eee67f663126490c2f96f40906594cb86b408a703630f95550a8c3e", size = 185044, upload-time = "2026-01-10T09:23:15.939Z" }, + { url = "https://files.pythonhosted.org/packages/ad/6e/9a0927ac24bd33a0a9af834d89e0abc7cfd8e13bed17a86407a66773cc0e/websockets-16.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:caab51a72c51973ca21fa8a18bd8165e1a0183f1ac7066a182ff27107b71e1a4", size = 186279, upload-time = "2026-01-10T09:23:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ca/bf1c68440d7a868180e11be653c85959502efd3a709323230314fda6e0b3/websockets-16.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:19c4dc84098e523fd63711e563077d39e90ec6702aff4b5d9e344a60cb3c0cb1", size = 185711, upload-time = "2026-01-10T09:23:18.372Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f8/fdc34643a989561f217bb477cbc47a3a07212cbda91c0e4389c43c296ebf/websockets-16.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5e18a238a2b2249c9a9235466b90e96ae4795672598a58772dd806edc7ac6d3", size = 184982, upload-time = "2026-01-10T09:23:19.652Z" }, + { url = "https://files.pythonhosted.org/packages/dd/d1/574fa27e233764dbac9c52730d63fcf2823b16f0856b3329fc6268d6ae4f/websockets-16.0-cp314-cp314-win32.whl", hash = "sha256:a069d734c4a043182729edd3e9f247c3b2a4035415a9172fd0f1b71658a320a8", size = 177915, upload-time = "2026-01-10T09:23:21.458Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f1/ae6b937bf3126b5134ce1f482365fde31a357c784ac51852978768b5eff4/websockets-16.0-cp314-cp314-win_amd64.whl", hash = "sha256:c0ee0e63f23914732c6d7e0cce24915c48f3f1512ec1d079ed01fc629dab269d", size = 178381, upload-time = "2026-01-10T09:23:22.715Z" }, + { url = "https://files.pythonhosted.org/packages/06/9b/f791d1db48403e1f0a27577a6beb37afae94254a8c6f08be4a23e4930bc0/websockets-16.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:a35539cacc3febb22b8f4d4a99cc79b104226a756aa7400adc722e83b0d03244", size = 177737, upload-time = "2026-01-10T09:23:24.523Z" }, + { url = "https://files.pythonhosted.org/packages/bd/40/53ad02341fa33b3ce489023f635367a4ac98b73570102ad2cdd770dacc9a/websockets-16.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:b784ca5de850f4ce93ec85d3269d24d4c82f22b7212023c974c401d4980ebc5e", size = 175268, upload-time = "2026-01-10T09:23:25.781Z" }, + { url = "https://files.pythonhosted.org/packages/74/9b/6158d4e459b984f949dcbbb0c5d270154c7618e11c01029b9bbd1bb4c4f9/websockets-16.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:569d01a4e7fba956c5ae4fc988f0d4e187900f5497ce46339c996dbf24f17641", size = 175486, upload-time = "2026-01-10T09:23:27.033Z" }, + { url = "https://files.pythonhosted.org/packages/e5/2d/7583b30208b639c8090206f95073646c2c9ffd66f44df967981a64f849ad/websockets-16.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:50f23cdd8343b984957e4077839841146f67a3d31ab0d00e6b824e74c5b2f6e8", size = 185331, upload-time = "2026-01-10T09:23:28.259Z" }, + { url = "https://files.pythonhosted.org/packages/45/b0/cce3784eb519b7b5ad680d14b9673a31ab8dcb7aad8b64d81709d2430aa8/websockets-16.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:152284a83a00c59b759697b7f9e9cddf4e3c7861dd0d964b472b70f78f89e80e", size = 186501, upload-time = "2026-01-10T09:23:29.449Z" }, + { url = "https://files.pythonhosted.org/packages/19/60/b8ebe4c7e89fb5f6cdf080623c9d92789a53636950f7abacfc33fe2b3135/websockets-16.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:bc59589ab64b0022385f429b94697348a6a234e8ce22544e3681b2e9331b5944", size = 186062, upload-time = "2026-01-10T09:23:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/88/a8/a080593f89b0138b6cba1b28f8df5673b5506f72879322288b031337c0b8/websockets-16.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32da954ffa2814258030e5a57bc73a3635463238e797c7375dc8091327434206", size = 185356, upload-time = "2026-01-10T09:23:32.627Z" }, + { url = "https://files.pythonhosted.org/packages/c2/b6/b9afed2afadddaf5ebb2afa801abf4b0868f42f8539bfe4b071b5266c9fe/websockets-16.0-cp314-cp314t-win32.whl", hash = "sha256:5a4b4cc550cb665dd8a47f868c8d04c8230f857363ad3c9caf7a0c3bf8c61ca6", size = 178085, upload-time = "2026-01-10T09:23:33.816Z" }, + { url = "https://files.pythonhosted.org/packages/9f/3e/28135a24e384493fa804216b79a6a6759a38cc4ff59118787b9fb693df93/websockets-16.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b14dc141ed6d2dde437cddb216004bcac6a1df0935d79656387bd41632ba0bbd", size = 178531, upload-time = "2026-01-10T09:23:35.016Z" }, + { url = "https://files.pythonhosted.org/packages/72/07/c98a68571dcf256e74f1f816b8cc5eae6eb2d3d5cfa44d37f801619d9166/websockets-16.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:349f83cd6c9a415428ee1005cadb5c2c56f4389bc06a9af16103c3bc3dcc8b7d", size = 174947, upload-time = "2026-01-10T09:23:36.166Z" }, + { url = "https://files.pythonhosted.org/packages/7e/52/93e166a81e0305b33fe416338be92ae863563fe7bce446b0f687b9df5aea/websockets-16.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:4a1aba3340a8dca8db6eb5a7986157f52eb9e436b74813764241981ca4888f03", size = 175260, upload-time = "2026-01-10T09:23:37.409Z" }, + { url = "https://files.pythonhosted.org/packages/56/0c/2dbf513bafd24889d33de2ff0368190a0e69f37bcfa19009ef819fe4d507/websockets-16.0-pp311-pypy311_pp73-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f4a32d1bd841d4bcbffdcb3d2ce50c09c3909fbead375ab28d0181af89fd04da", size = 176071, upload-time = "2026-01-10T09:23:39.158Z" }, + { url = "https://files.pythonhosted.org/packages/a5/8f/aea9c71cc92bf9b6cc0f7f70df8f0b420636b6c96ef4feee1e16f80f75dd/websockets-16.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0298d07ee155e2e9fda5be8a9042200dd2e3bb0b8a38482156576f863a9d457c", size = 176968, upload-time = "2026-01-10T09:23:41.031Z" }, + { url = "https://files.pythonhosted.org/packages/9a/3f/f70e03f40ffc9a30d817eef7da1be72ee4956ba8d7255c399a01b135902a/websockets-16.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:a653aea902e0324b52f1613332ddf50b00c06fdaf7e92624fbf8c77c78fa5767", size = 178735, upload-time = "2026-01-10T09:23:42.259Z" }, + { url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" }, +] + [[package]] name = "yarl" version = "1.20.1" From d1039d50dca762adf52043167903d7a48960f6ed Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:14 +0200 Subject: [PATCH 02/10] feat(copilot-app): add project resolver with SQLite fallback New module copilot_app_project.py: frozen dataclasses for RepoContext / ProjectRecipe / ResolvedProject, pure derivers (derive_repo_context, derive_project_recipe), and resolve_or_register_project_sqlite that SELECTs by main_repo_path or INSERTs a fresh row inside BEGIN IMMEDIATE. Race-collision recovery: on sqlite3.IntegrityError, re- SELECT inside the same transaction to return the winning id. Backed by 14 unit tests covering the no-repo / HTTPS / SSH / non- github / subdir-walk-up derive paths and HIT / MISS / external-row / race-recovery / missing-db / schema-too-new resolver branches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../integration/copilot_app_project.py | 401 ++++++++++++++++++ .../integration/test_copilot_app_project.py | 351 +++++++++++++++ 2 files changed, 752 insertions(+) create mode 100644 src/apm_cli/integration/copilot_app_project.py create mode 100644 tests/unit/integration/test_copilot_app_project.py diff --git a/src/apm_cli/integration/copilot_app_project.py b/src/apm_cli/integration/copilot_app_project.py new file mode 100644 index 0000000000..a1b98c10dc --- /dev/null +++ b/src/apm_cli/integration/copilot_app_project.py @@ -0,0 +1,401 @@ +"""Project derivation and SQLite-fallback resolver for the Copilot App. + +The Copilot App's ``workflows`` table carries a ``project_id`` foreign- +key into ``projects(id)``. APM-deployed workflow rows must point at the +project that "owns" the prompt (the repository the user ran +``apm install`` from) so that "Run now" in the App's Workflows tab CWDs +into the right repo, and the row groups under the correct sidebar entry. + +This module is the pure derive / resolve layer. It has two halves: + +1. **derive_** -- ``RepoContext`` from a path on disk, ``ProjectRecipe`` + from a ``RepoContext``. Both are pure: no I/O on the App's DB, no + network calls. Easy to unit-test against tmp dirs. + +2. **resolve_or_register_project_sqlite** -- the SQLite-fallback path + used when the Copilot App is closed (the WebSocket IPC surface is + unavailable). Issues a single ``BEGIN IMMEDIATE`` transaction: + SELECT by ``main_repo_path`` (UNIQUE), INSERT if missing. Reuses + ``copilot_app_db._connect`` / ``_check_user_version`` / + ``_begin_immediate_with_retry`` for WAL-safe semantics consistent + with the workflow writer. + +The WS-IPC happy path lives in ``copilot_app_ws.py`` and short-circuits +this module's resolver; only the fallback path executes here. + +Security note +------------- +``derive_repo_context`` walks parents looking for ``.git/``. We do not +follow symlinks and we do not invoke ``git`` as a subprocess; the +``GitPython`` API reads pack files / refs directly. ``main_repo_path`` +is always stored as an absolute, resolved path so two clones of the +same repo at different filesystem locations cannot collide on the +``projects.main_repo_path UNIQUE`` constraint. +""" + +from __future__ import annotations + +import re +import sqlite3 +import uuid +from dataclasses import dataclass +from pathlib import Path + +from apm_cli.integration.copilot_app_db import ( + CopilotAppDbError, + CopilotAppDbMissingError, + _begin_immediate_with_retry, + _check_user_version, + _connect, +) + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +_DEFAULT_BRANCH: str = "main" +"""Fallback branch name when the repo has no remote HEAD reference.""" + +_GH_REMOTE_RE: re.Pattern[str] = re.compile( + r""" + (?:https?://github\.com/|git@github\.com:|github\.com/) + (?P[A-Za-z0-9_.-]+)/ + (?P[A-Za-z0-9_.-]+?) + (?:\.git)?/?$ + """, + re.VERBOSE, +) +"""Match the GitHub portion of a typical ``origin`` URL. + +Tolerates ``https://github.com/o/r``, ``https://github.com/o/r.git``, +``git@github.com:o/r.git``, and the ``ssh://git@github.com/o/r.git`` +shapes commonly produced by ``git clone`` against github.com. +""" + + +# --------------------------------------------------------------------------- +# Value objects (frozen dataclasses -- safe across worker threads) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class RepoContext: + """Information derived from the on-disk repository root. + + Captured once at install time and shared between the project- + resolver and the workflow-writer so display names + ``main_repo_path`` + stay consistent across the install transaction. + """ + + repo_root: Path + """Absolute, resolved path to the repo's working tree root. + + Stored verbatim in ``projects.main_repo_path`` (the column is + UNIQUE in the App's schema). Two checkouts of the same repo at + different paths will resolve to two ``projects`` rows -- which is + correct: the App tracks projects by filesystem location, not by + GitHub identity. + """ + + repo_name: str + """Best-effort repo display label. + + Resolution order: ``origin``'s repo segment -> ``repo_root.name`` -> + ``"project"``. Used both as ``projects.name`` and as the suffix on + each workflow row's display name (`` ()``). + """ + + github_owner: str | None + """GitHub owner (org / user) parsed from ``origin``. ``None`` when + the repo has no ``origin`` or the URL isn't github.com-shaped.""" + + github_repo: str | None + """GitHub repo name parsed from ``origin``. ``None`` under the same + conditions as ``github_owner``.""" + + default_branch: str + """The repo's active branch when discovery happened, falling back to + ``main`` when detection fails. The App stores this in + ``projects.default_branch`` purely for display in the sidebar; it + has no functional effect on workflow execution.""" + + +@dataclass(frozen=True) +class ProjectRecipe: + """The exact set of column values APM writes to ``projects``. + + Mirrors the live recipe captured in ``livedb-findings.md`` (the + diff produced by the App's own "Add project" flow). Kept as a + dataclass so the SQLite-fallback resolver and any future + direct-write path share one canonical shape. + """ + + id: str + """Dashed UUIDv4 string -- ``str(uuid.uuid4())`` -- 36 chars. The + App accepts any non-empty TEXT but generates dashed UUIDs itself, + so APM matches for visual parity in the App's debug tooling.""" + + name: str + """Human-readable label -- equal to ``RepoContext.repo_name``.""" + + main_repo_path: str + """Absolute repo root path. UNIQUE in the ``projects`` table; the + resolver uses it as the lookup key for HIT/MISS detection.""" + + default_branch: str + """Branch shown in the sidebar; no execution semantics.""" + + github_owner: str | None + github_repo: str | None + + +@dataclass(frozen=True) +class ResolvedProject: + """Outcome of resolving (or registering) a project row. + + ``was_created`` drives the "restart Copilot App once" diagnostic + in the integrator (see github/github-app#5483 for why projects + don't live-refresh in the sidebar without a restart). + """ + + project_id: str + """The ``projects.id`` value (either pre-existing or freshly + INSERTed).""" + + was_created: bool + """True iff this call INSERTed a new row. Drives one-shot UX + diagnostics like the restart hint.""" + + main_repo_path: str + """Echo of the resolved row's ``main_repo_path`` for callers that + want to stamp the workflow's CWD without re-reading the row.""" + + +# --------------------------------------------------------------------------- +# Pure derive_* helpers +# --------------------------------------------------------------------------- + + +def _safe_repo(repo_root: Path): + """Open a ``GitPython`` repo handle without raising on missing ``.git``. + + Returns ``None`` when *repo_root* is not a git working tree. Used by + every metadata probe below so the rest of the function can stay + branch-light. + """ + try: + from git import InvalidGitRepositoryError, Repo + except ImportError: + return None + try: + return Repo(repo_root) + except (InvalidGitRepositoryError, Exception): + return None + + +def _find_repo_root(start: Path) -> Path | None: + """Walk *start* and its parents looking for a ``.git`` directory. + + Returns the first ancestor containing ``.git`` (file or dir -- git + worktrees use a file pointer), or ``None`` when no enclosing repo + is found. Symlinks in the chain are not followed (defense against + being lured into an attacker-controlled root). + """ + start = start.resolve() + for candidate in (start, *start.parents): + git_marker = candidate / ".git" + if git_marker.exists() and not git_marker.is_symlink(): + return candidate + return None + + +def _parse_github_origin(url: str) -> tuple[str | None, str | None]: + """Parse ``owner, repo`` from a GitHub-shaped URL or return ``(None, None)``.""" + m = _GH_REMOTE_RE.search(url.strip()) + if not m: + return None, None + return m.group("owner"), m.group("repo") + + +def derive_repo_context(cwd: Path) -> RepoContext | None: + """Derive a ``RepoContext`` from *cwd* (or any path inside a repo). + + Returns ``None`` when *cwd* is not inside any git working tree -- + callers MUST treat this as "cannot attach to a project" and + surface a diagnostic rather than silently inventing one (a + NULL-project workflow CWDs into ``~/.copilot``, which is a real + security finding -- see reverse-eng report). + + Best-effort fields (``github_owner``, ``github_repo``, + ``default_branch``) degrade gracefully when the repo has no + ``origin`` or detached HEAD; we never raise for missing optional + metadata. + """ + repo_root = _find_repo_root(cwd) + if repo_root is None: + return None + + owner: str | None = None + repo_name_from_remote: str | None = None + branch: str = _DEFAULT_BRANCH + + repo = _safe_repo(repo_root) + if repo is not None: + import contextlib + + with contextlib.suppress(AttributeError, ValueError, Exception): + origin_url = repo.remotes.origin.url + owner, repo_name_from_remote = _parse_github_origin(origin_url) + with contextlib.suppress(TypeError, ValueError, Exception): + # Detached HEAD or bare repo -- accept the default. + branch = repo.active_branch.name or _DEFAULT_BRANCH + + repo_name = repo_name_from_remote or repo_root.name or "project" + + return RepoContext( + repo_root=repo_root, + repo_name=repo_name, + github_owner=owner, + github_repo=repo_name_from_remote, + default_branch=branch, + ) + + +def derive_project_recipe(ctx: RepoContext) -> ProjectRecipe: + """Translate a ``RepoContext`` into the columns APM writes to ``projects``. + + Generates a fresh dashed UUIDv4 -- callers wishing to compare + recipes (e.g. for idempotent INSERT) should NOT use ``id`` as a + key; ``main_repo_path`` is the App's UNIQUE column and the only + stable identity. + """ + return ProjectRecipe( + id=str(uuid.uuid4()), + name=ctx.repo_name, + main_repo_path=str(ctx.repo_root), + default_branch=ctx.default_branch, + github_owner=ctx.github_owner, + github_repo=ctx.github_repo, + ) + + +# --------------------------------------------------------------------------- +# SQLite fallback resolver +# --------------------------------------------------------------------------- + + +_PROJECTS_INSERT_SQL: str = """ +INSERT INTO projects ( + id, name, container_kind, main_repo_path, default_branch, + github_owner, github_repo, auto_open_in_browser, auto_approve +) VALUES (?, ?, 'repository', ?, ?, ?, ?, 1, 1) +""" +"""Minimum-viable ``projects`` row recipe. + +Mirrors the live diff captured in ``livedb-findings.md``: only the +columns the App's own "Add project" flow populates by default. We +deliberately omit ``tab_order`` (NULL on fresh projects), +``github_account_id`` (the App resolves at session time), and the +optional ``issue_prompt`` / ``pull_request_prompt`` template columns +(the App falls back to its bundled defaults when these are NULL). +``container_kind='repository'`` matches the only kind the sidebar +renders for filesystem-anchored projects. +""" + + +def resolve_or_register_project_sqlite( + db_path: Path, + ctx: RepoContext, +) -> ResolvedProject: + """Look up or insert a ``projects`` row for *ctx*'s repo. + + Used as the fallback when the Copilot App's WebSocket IPC surface + is unavailable (i.e. the App is not running). Single + ``BEGIN IMMEDIATE`` transaction: + + 1. ``SELECT id, main_repo_path FROM projects WHERE main_repo_path=?`` + -- HIT means the App (or a prior APM install) already knows this + repo; reuse the ``id``. + 2. ``INSERT INTO projects (...) VALUES (...)`` with the recipe + returned by ``derive_project_recipe``. Race-collision (another + writer beat us) is recovered by re-SELECTing inside the same + transaction so the caller always sees a stable id. + + Raises: + CopilotAppDbMissingError: ``db_path`` does not exist. + CopilotAppDbSchemaError: ``PRAGMA user_version`` is out of range + (delegated to ``_check_user_version``). + CopilotAppDbLockedError: ``BEGIN IMMEDIATE`` timed out. + """ + if not db_path.is_file(): + raise CopilotAppDbMissingError( + f"Copilot App database not found at {db_path}. " + f"Install the GitHub Copilot desktop app, or omit " + f"'--target copilot-app'." + ) + + conn = _connect(db_path) + try: + _check_user_version(conn) + _begin_immediate_with_retry(conn) + try: + existing = conn.execute( + "SELECT id, main_repo_path FROM projects WHERE main_repo_path = ?", + (str(ctx.repo_root),), + ).fetchone() + if existing is not None: + conn.execute("COMMIT") + return ResolvedProject( + project_id=existing["id"], + was_created=False, + main_repo_path=existing["main_repo_path"], + ) + + recipe = derive_project_recipe(ctx) + try: + conn.execute( + _PROJECTS_INSERT_SQL, + ( + recipe.id, + recipe.name, + recipe.main_repo_path, + recipe.default_branch, + recipe.github_owner, + recipe.github_repo, + ), + ) + except sqlite3.IntegrityError: + # Race: another writer (the App itself, or a parallel + # apm install) inserted the same main_repo_path between + # our SELECT and INSERT. Re-read inside this transaction + # to find the winner's id. + row = conn.execute( + "SELECT id, main_repo_path FROM projects WHERE main_repo_path = ?", + (str(ctx.repo_root),), + ).fetchone() + if row is None: + # IntegrityError but no matching row -- some other + # constraint failed (e.g. NOT NULL on a column we + # don't write). Surface as a DB error. + raise CopilotAppDbError( + "Race recovery failed: project row INSERT collided " + "but no matching row was found post-collision." + ) from None + conn.execute("COMMIT") + return ResolvedProject( + project_id=row["id"], + was_created=False, + main_repo_path=row["main_repo_path"], + ) + + conn.execute("COMMIT") + return ResolvedProject( + project_id=recipe.id, + was_created=True, + main_repo_path=recipe.main_repo_path, + ) + except Exception: + conn.execute("ROLLBACK") + raise + finally: + conn.close() diff --git a/tests/unit/integration/test_copilot_app_project.py b/tests/unit/integration/test_copilot_app_project.py new file mode 100644 index 0000000000..ec3cac86a4 --- /dev/null +++ b/tests/unit/integration/test_copilot_app_project.py @@ -0,0 +1,351 @@ +"""Unit tests for ``apm_cli.integration.copilot_app_project``. + +Covers: + +* ``derive_repo_context`` -- no-repo / no-remote / GitHub-remote / + detached-HEAD branches. +* ``derive_project_recipe`` -- pure projection. +* ``resolve_or_register_project_sqlite`` -- MISS (INSERT), + HIT (SELECT-only), race-collision recovery, missing-DB error, + malformed schema rejection. +""" + +from __future__ import annotations + +import sqlite3 +import subprocess +from pathlib import Path + +import pytest + +from apm_cli.integration import copilot_app_db as cdb +from apm_cli.integration import copilot_app_project as cap + +# --------------------------------------------------------------------------- +# Schema fixture -- includes the workflows table (required by user_version +# guard) plus the projects table (subject under test). +# --------------------------------------------------------------------------- + +_SCHEMA: str = """ +CREATE TABLE IF NOT EXISTS "projects" ( + id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + container_kind TEXT NOT NULL, + main_repo_path TEXT UNIQUE, + default_branch TEXT, + github_owner TEXT, + github_repo TEXT, + github_account_id TEXT, + tab_order INTEGER, + issue_prompt TEXT, + pull_request_prompt TEXT, + auto_open_in_browser INTEGER NOT NULL DEFAULT 1, + auto_approve INTEGER NOT NULL DEFAULT 1 +); +CREATE TABLE IF NOT EXISTS "workflows" ( + id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + prompt TEXT NOT NULL, + interval TEXT NOT NULL CHECK (interval IN ('manual', 'hourly', 'daily', 'weekly')), + schedule_hour INTEGER NOT NULL DEFAULT 9, + schedule_day INTEGER NOT NULL DEFAULT 1, + enabled INTEGER NOT NULL DEFAULT 1, + project_id TEXT, + mode TEXT +); +""" + + +def _make_db(path: Path, user_version: int = 13) -> Path: + conn = sqlite3.connect(str(path)) + try: + conn.executescript(_SCHEMA) + conn.execute(f"PRAGMA user_version = {user_version}") + conn.commit() + finally: + conn.close() + return path + + +@pytest.fixture +def db_path(tmp_path: Path) -> Path: + return _make_db(tmp_path / "data.db") + + +def _git_init(repo_root: Path, *, remote: str | None = None) -> None: + """Minimal local git init so derive_repo_context has something to bite.""" + repo_root.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["git", "init", "-q", "-b", "main"], + cwd=repo_root, + check=True, + ) + subprocess.run( + ["git", "config", "user.email", "t@t"], + cwd=repo_root, + check=True, + ) + subprocess.run( + ["git", "config", "user.name", "t"], + cwd=repo_root, + check=True, + ) + if remote is not None: + subprocess.run( + ["git", "remote", "add", "origin", remote], + cwd=repo_root, + check=True, + ) + + +# --------------------------------------------------------------------------- +# Pure derive_* tests. +# --------------------------------------------------------------------------- + + +class TestDeriveRepoContext: + def test_no_repo_returns_none(self, tmp_path: Path) -> None: + assert cap.derive_repo_context(tmp_path) is None + + def test_plain_repo_no_remote(self, tmp_path: Path) -> None: + repo = tmp_path / "my-repo" + _git_init(repo) + ctx = cap.derive_repo_context(repo) + assert ctx is not None + assert ctx.repo_root == repo.resolve() + assert ctx.repo_name == "my-repo" + assert ctx.github_owner is None + assert ctx.github_repo is None + # default_branch defaults to "main" when detection succeeds OR + # when it fails -- either way the field is populated. + assert ctx.default_branch + + def test_github_https_remote(self, tmp_path: Path) -> None: + repo = tmp_path / "demo" + _git_init(repo, remote="https://github.com/octo/widgets.git") + ctx = cap.derive_repo_context(repo) + assert ctx is not None + assert ctx.github_owner == "octo" + assert ctx.github_repo == "widgets" + # repo_name prefers the remote-derived name over folder name. + assert ctx.repo_name == "widgets" + + def test_github_ssh_remote(self, tmp_path: Path) -> None: + repo = tmp_path / "demo2" + _git_init(repo, remote="git@github.com:octo/widgets.git") + ctx = cap.derive_repo_context(repo) + assert ctx is not None + assert ctx.github_owner == "octo" + assert ctx.github_repo == "widgets" + + def test_non_github_remote_yields_none_owner(self, tmp_path: Path) -> None: + repo = tmp_path / "demo3" + _git_init(repo, remote="https://gitlab.com/octo/widgets.git") + ctx = cap.derive_repo_context(repo) + assert ctx is not None + assert ctx.github_owner is None + assert ctx.github_repo is None + # repo_name falls back to folder name. + assert ctx.repo_name == "demo3" + + def test_finds_repo_root_from_subdir(self, tmp_path: Path) -> None: + repo = tmp_path / "root" + _git_init(repo) + subdir = repo / "a" / "b" + subdir.mkdir(parents=True) + ctx = cap.derive_repo_context(subdir) + assert ctx is not None + assert ctx.repo_root == repo.resolve() + + +class TestDeriveProjectRecipe: + def test_pure_projection(self) -> None: + ctx = cap.RepoContext( + repo_root=Path("/tmp/x"), + repo_name="x", + github_owner="o", + github_repo="x", + default_branch="main", + ) + r = cap.derive_project_recipe(ctx) + assert r.name == "x" + assert r.main_repo_path == "/tmp/x" + assert r.default_branch == "main" + assert r.github_owner == "o" + assert r.github_repo == "x" + # Dashed UUID4 -- 36 chars including hyphens. + assert len(r.id) == 36 + assert r.id.count("-") == 4 + + +# --------------------------------------------------------------------------- +# resolve_or_register_project_sqlite tests. +# --------------------------------------------------------------------------- + + +def _make_ctx(repo: Path, *, repo_name: str = "demo") -> cap.RepoContext: + return cap.RepoContext( + repo_root=repo.resolve(), + repo_name=repo_name, + github_owner="octo", + github_repo=repo_name, + default_branch="main", + ) + + +class TestResolverMiss: + def test_insert_creates_row(self, db_path: Path, tmp_path: Path) -> None: + repo = tmp_path / "miss-repo" + repo.mkdir() + ctx = _make_ctx(repo) + resolved = cap.resolve_or_register_project_sqlite(db_path, ctx) + assert resolved.was_created is True + assert resolved.project_id # non-empty + assert resolved.main_repo_path == str(repo.resolve()) + # Verify row landed with the expected shape. + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + try: + row = conn.execute( + "SELECT * FROM projects WHERE id = ?", + (resolved.project_id,), + ).fetchone() + assert row is not None + assert row["name"] == "demo" + assert row["main_repo_path"] == str(repo.resolve()) + assert row["container_kind"] == "repository" + assert row["default_branch"] == "main" + assert row["github_owner"] == "octo" + finally: + conn.close() + + +class TestResolverHit: + def test_returns_existing_id_without_insert(self, db_path: Path, tmp_path: Path) -> None: + repo = tmp_path / "hit-repo" + repo.mkdir() + ctx = _make_ctx(repo) + first = cap.resolve_or_register_project_sqlite(db_path, ctx) + second = cap.resolve_or_register_project_sqlite(db_path, ctx) + assert first.was_created is True + assert second.was_created is False + assert first.project_id == second.project_id + + def test_external_row_is_reused(self, db_path: Path, tmp_path: Path) -> None: + """An existing App-native row (different id) is reused, not duplicated.""" + repo = tmp_path / "external-repo" + repo.mkdir() + external_id = "ffffffff-0000-4000-8000-000000000001" + conn = sqlite3.connect(str(db_path)) + try: + conn.execute( + "INSERT INTO projects (id, name, container_kind, main_repo_path) " + "VALUES (?, ?, 'repository', ?)", + (external_id, "demo", str(repo.resolve())), + ) + conn.commit() + finally: + conn.close() + resolved = cap.resolve_or_register_project_sqlite(db_path, _make_ctx(repo)) + assert resolved.was_created is False + assert resolved.project_id == external_id + + +class TestResolverErrors: + def test_missing_db_raises_missing_error(self, tmp_path: Path) -> None: + repo = tmp_path / "norepo" + repo.mkdir() + with pytest.raises(cdb.CopilotAppDbMissingError, match=r"not found"): + cap.resolve_or_register_project_sqlite(tmp_path / "absent.db", _make_ctx(repo)) + + def test_schema_too_new_raises(self, tmp_path: Path) -> None: + bad = _make_db(tmp_path / "newer.db", user_version=999) + repo = tmp_path / "r" + repo.mkdir() + with pytest.raises(cdb.CopilotAppDbSchemaError): + cap.resolve_or_register_project_sqlite(bad, _make_ctx(repo)) + + +class TestRaceCollisionRecovery: + def test_race_collision_resolves_to_winning_id( + self, db_path: Path, tmp_path: Path, monkeypatch + ) -> None: + """Simulate concurrent INSERT mid-transaction. + + Captures the connection the resolver opens via ``_connect``, then + monkeypatches ``derive_project_recipe`` (called between SELECT + and INSERT) to insert a colliding row on the SAME connection so + the resolver's INSERT trips ``sqlite3.IntegrityError`` and falls + into the race-recovery SELECT branch. + """ + repo = tmp_path / "race-repo" + repo.mkdir() + winning_id = "11111111-2222-4333-8444-555555555555" + + captured: dict[str, sqlite3.Connection] = {} + real_connect = cap._connect + + def capturing_connect(path): + conn = real_connect(path) + captured["c"] = conn + return conn + + monkeypatch.setattr(cap, "_connect", capturing_connect) + + real_derive = cap.derive_project_recipe + + def colliding_derive(ctx): + recipe = real_derive(ctx) + conn = captured["c"] + conn.execute( + "INSERT INTO projects (id, name, container_kind, main_repo_path) " + "VALUES (?, ?, 'repository', ?)", + (winning_id, ctx.repo_name, str(ctx.repo_root)), + ) + return recipe + + monkeypatch.setattr(cap, "derive_project_recipe", colliding_derive) + resolved = cap.resolve_or_register_project_sqlite(db_path, _make_ctx(repo)) + # Race recovery returns the WINNING (external) id, not our recipe id. + assert resolved.project_id == winning_id + assert resolved.was_created is False + + def test_race_collision_no_recovery_row_raises( + self, db_path: Path, tmp_path: Path, monkeypatch + ) -> None: + """IntegrityError on a different constraint surfaces as a DB error. + + Patches ``derive_project_recipe`` to return a recipe whose ``id`` + collides with a pre-existing row that has a DIFFERENT + ``main_repo_path``, so the race-recovery SELECT finds nothing + for our path. The resolver MUST raise rather than silently + invent a project id. + """ + repo = tmp_path / "no-recover-repo" + repo.mkdir() + clashing_id = "22222222-3333-4444-8555-666666666666" + conn = sqlite3.connect(str(db_path)) + try: + conn.execute( + "INSERT INTO projects (id, name, container_kind, main_repo_path) " + "VALUES (?, ?, 'repository', ?)", + (clashing_id, "other", str(tmp_path / "other-path")), + ) + conn.commit() + finally: + conn.close() + + def clashing_derive(ctx): + base = cap.ProjectRecipe( + id=clashing_id, + name=ctx.repo_name, + main_repo_path=str(ctx.repo_root), + default_branch="main", + github_owner=None, + github_repo=None, + ) + return base + + monkeypatch.setattr(cap, "derive_project_recipe", clashing_derive) + with pytest.raises(cdb.CopilotAppDbError, match=r"Race recovery"): + cap.resolve_or_register_project_sqlite(db_path, _make_ctx(repo)) From 288b05c41d371e6ba0451d613d95f8738a9a8113 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:14 +0200 Subject: [PATCH 03/10] feat(copilot-app): add sync WS-IPC client for live App integration New module copilot_app_ws.py: WsClient context manager using websockets.sync.client (no asyncio in install loop), ws_available() liveness probe bounded to 100ms, and create_project_from_path / create_workflow / update_workflow RPCs. Custom exceptions (WsAppNotRunning / WsAuthError / WsProtocolError) let the caller distinguish silent fallback from warn-and-fallback. Reads ~/.copilot/run/ws.{port,token}, presents Origin: tauri:// localhost (the App rejects any other Origin), and walks past interleaved server push frames to find the response to our request. Permissive JSON parser tolerates unknown / added top-level fields so upstream schema additions don't break us. Backed by 19 unit tests against a real websockets.sync.server harness covering handshake / auth / origin / round-trip / drain / timeout. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/integration/copilot_app_ws.py | 564 ++++++++++++++++++ tests/unit/integration/test_copilot_app_ws.py | 366 ++++++++++++ 2 files changed, 930 insertions(+) create mode 100644 src/apm_cli/integration/copilot_app_ws.py create mode 100644 tests/unit/integration/test_copilot_app_ws.py diff --git a/src/apm_cli/integration/copilot_app_ws.py b/src/apm_cli/integration/copilot_app_ws.py new file mode 100644 index 0000000000..7236a5ac29 --- /dev/null +++ b/src/apm_cli/integration/copilot_app_ws.py @@ -0,0 +1,564 @@ +"""Localhost WebSocket IPC client for the GitHub Copilot desktop App. + +The App binds a per-launch authenticated WebSocket on ``127.0.0.1:`` +and writes the port and token to ``~/.copilot/run/ws.{port,token}`` +(mode 0o600). Any local process that can read those files can speak +the full ``WsClientMessage`` dialect. This module is the typed, +synchronous, scope-limited Python client APM uses to: + +* register a project from a filesystem path (``create_project_from_path``), +* create or update an APM-managed workflow row attached to that + project (``create_workflow`` / ``update_workflow``). + +The WS path is the **preferred** integration surface when the App is +running: it goes through the App's own validation, fires the global +``WorkflowsChanged`` broadcast so the Workflows tab live-refreshes, +and avoids the white-screen failure mode where the webview cannot +resolve an externally-written ``project_id`` (see reverse-eng report). +When the App is closed the WS surface is unavailable and the caller +falls back to direct SQLite via ``copilot_app_project``. + +Synchronous by design +--------------------- +The install loop is fully synchronous; spinning up an asyncio loop +would force every primitive call site (``prompt_integrator``) into the +``asyncio.run`` ceremony with no benefit. We use +``websockets.sync.client.connect`` -- the official sync API shipped in +``websockets>=12`` -- which gives us blocking ``send``/``recv`` with +timeouts. + +Security posture +---------------- +We mirror the App's own webview behaviour: + +* Always present ``Origin: tauri://localhost``. The server rejects + any other origin (``websocket.rs:489-525``). +* Token is supplied via the ``?token=`` query string the + server expects. +* TCP probe in ``ws_available`` is bounded to 100ms so install never + hangs when the port file is stale (App crashed without cleanup). +* Parser is permissive: tolerate unknown / added top-level fields so + upstream additions don't break us. We extract only what we use. +""" + +from __future__ import annotations + +import json +import os +import socket +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +_RUN_DIR: str = ".copilot/run" +"""Directory under ``~/`` where the App publishes its port + token.""" + +_PORT_FILE: str = "ws.port" +_TOKEN_FILE: str = "ws.token" # noqa: S105 + +_TCP_PROBE_TIMEOUT_S: float = 0.1 +"""Liveness-probe budget: 100ms is plenty for a localhost connect and +keeps install responsive when the port file is stale (App crashed).""" + +_WS_HANDSHAKE_TIMEOUT_S: float = 3.0 +"""Maximum time to wait for the WS handshake to complete.""" + +_WS_RECV_TIMEOUT_S: float = 5.0 +"""Default per-message recv timeout. Server replies arrive immediately +on localhost; this is a generous safety net against unexpected hangs.""" + +_ORIGIN_HEADER: str = "tauri://localhost" +"""The Origin value the App's WS server accepts (mirrors the bundled +webview's own Origin). Any other value is rejected at the gate.""" + +_USER_AGENT: str = "apm-cli/copilot-app-ws" +"""Recognisable UA string so the App's connection logs / telemetry can +attribute traffic to APM rather than the webview itself.""" + + +# --------------------------------------------------------------------------- +# Exceptions +# --------------------------------------------------------------------------- + + +class WsError(Exception): + """Base class for any WS-IPC failure. + + Callers in the integrator catch this to fall back to the direct- + SQLite path; sub-types let UX code distinguish "App isn't running" + (silent fallback, expected) from "App is running but rejected us" + (warn-and-fall-back, surprising). + """ + + +class WsAppNotRunning(WsError): + """Port file missing or TCP probe failed -- the App is closed. + + Triggers silent fallback to SQLite. Not a user-visible warning: + closed App is the normal off-state. + """ + + +class WsAuthError(WsError): + """Token rejected during handshake. + + Most common cause: stale ``~/.copilot/run/ws.token`` after an App + restart. We warn-and-fall-back so install still succeeds. + """ + + +class WsProtocolError(WsError): + """Server returned an error message or a malformed reply we cannot + parse. Indicates either an upstream schema drift or a true server- + side failure (e.g. ``create_project_from_path`` for a non-existent + folder).""" + + +# --------------------------------------------------------------------------- +# Liveness probe +# --------------------------------------------------------------------------- + + +_RUN_DIR_ENV: str = "APM_COPILOT_APP_WS_RUN_DIR" +"""Environment override for the run-files directory. Tests and CI use +this to point at a fixture directory; production leaves it unset and +falls through to ``~/.copilot/run``.""" + + +def _run_dir() -> Path: + """Resolve the App's run-files directory. + + Honours ``APM_COPILOT_APP_WS_RUN_DIR`` (intended for tests / CI), + otherwise falls back to ``~/.copilot/run``. Lazy so tests can + monkeypatch ``Path.home`` or the env var per-test. + """ + override = os.environ.get(_RUN_DIR_ENV) + if override: + return Path(override) + return Path.home() / _RUN_DIR + + +def _read_creds() -> tuple[int, str] | None: + """Return ``(port, token)`` from the App's run-files or ``None``. + + Both files must exist and be readable; either missing means the App + is not running (or never has been since boot). We do not validate + the token format here -- the server rejects invalid tokens at + handshake. + """ + run = _run_dir() + port_path = run / _PORT_FILE + token_path = run / _TOKEN_FILE + if not port_path.is_file() or not token_path.is_file(): + return None + try: + port = int(port_path.read_text(encoding="ascii").strip()) + token = token_path.read_text(encoding="ascii").strip() + except (OSError, ValueError): + return None + if not (0 < port < 65536) or not token: + return None + return port, token + + +def ws_available() -> bool: + """Quick liveness check: port file present AND TCP probe succeeds. + + Bounded to ``_TCP_PROBE_TIMEOUT_S`` so a stale port file (App + crashed without cleanup) never costs the user more than 100ms on + install. Returns ``False`` on any failure -- callers fall through + to the SQLite path silently. + """ + creds = _read_creds() + if creds is None: + return False + port, _token = creds + try: + with socket.create_connection(("127.0.0.1", port), timeout=_TCP_PROBE_TIMEOUT_S): + return True + except (OSError, ValueError): + return False + + +# --------------------------------------------------------------------------- +# Response value objects (permissive: extra fields ignored) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ProjectCreated: + """Outcome of ``create_project_from_path``. + + ``was_created`` is ``True`` only on a fresh INSERT. When the App + already had a row for the given path (HIT) it returns the existing + id and ``was_created`` is ``False`` -- drives the restart-once UX + hint exactly like the SQLite fallback. + """ + + project_id: str + was_created: bool + main_repo_path: str + + +@dataclass(frozen=True) +class WorkflowCreated: + """Outcome of ``create_workflow`` / ``update_workflow``. + + The App generates a UUIDv4 for new rows. APM's caller does not + depend on the format -- the id is opaque and only used to address + the row in subsequent ``update_workflow`` / delete calls. + """ + + workflow_id: str + + +# --------------------------------------------------------------------------- +# Client +# --------------------------------------------------------------------------- + + +class WsClient: + """Synchronous WS-IPC client. + + Use as a context manager so the underlying socket is closed even + when an exception propagates:: + + with WsClient() as client: + project = client.create_project_from_path(repo_root) + for wf in workflows: + client.create_workflow(...) + + All public methods raise a ``WsError`` subtype on any failure; the + caller in ``prompt_integrator._integrate_prompts_for_copilot_app`` + catches ``WsError`` and falls through to the SQLite path. + """ + + def __init__(self, *, recv_timeout_s: float = _WS_RECV_TIMEOUT_S) -> None: + self._recv_timeout_s = recv_timeout_s + self._conn: Any | None = None + + # -- lifecycle ------------------------------------------------------ + + def __enter__(self) -> WsClient: + self._connect() + # Drain greeting messages (server_hello + a few housekeeping + # broadcasts) so subsequent recv calls see the response to our + # next send, not stale greetings. + self._drain(timeout_s=0.5) + return self + + def __exit__(self, exc_type, exc, tb) -> None: + self.close() + + def close(self) -> None: + """Close the underlying socket. Idempotent.""" + import contextlib + + if self._conn is not None: + with contextlib.suppress(Exception): + self._conn.close() + self._conn = None + + # -- connection ----------------------------------------------------- + + def _connect(self) -> None: + """Open the authenticated WS connection. + + Raises: + WsAppNotRunning: port/token files missing or TCP refused. + WsAuthError: server rejected the token at handshake. + WsProtocolError: any other handshake failure. + """ + # Lazy import: websockets is a hard dep but the import cost is + # non-trivial and only matters when the App is running. + try: + from websockets.sync.client import connect + except ImportError as exc: # pragma: no cover - hard dep + raise WsError(f"websockets library unavailable: {exc}") from exc + + creds = _read_creds() + if creds is None: + raise WsAppNotRunning("No ~/.copilot/run/ws.{port,token} files present") + port, token = creds + + url = f"ws://127.0.0.1:{port}/?token={token}" + try: + self._conn = connect( + url, + additional_headers={ + "Origin": _ORIGIN_HEADER, + "User-Agent": _USER_AGENT, + }, + open_timeout=_WS_HANDSHAKE_TIMEOUT_S, + max_size=2**24, + ) + except Exception as exc: + msg = str(exc) + # ``websockets`` raises InvalidStatus / InvalidHandshake for + # HTTP-level rejections. 401/403 -> auth; everything else -> + # generic protocol error. We string-match defensively so a + # library-version bump doesn't break the branch. + if "401" in msg or "403" in msg or "unauthor" in msg.lower(): + raise WsAuthError(f"WS auth rejected: {exc}") from exc + if "refused" in msg.lower() or "ConnectionRefused" in msg: + raise WsAppNotRunning(f"WS connection refused: {exc}") from exc + raise WsProtocolError(f"WS handshake failed: {exc}") from exc + + # -- low-level send/recv ------------------------------------------- + + def _send(self, payload: dict[str, Any]) -> None: + """Serialize *payload* as JSON and send. Raises ``WsError`` on failure.""" + if self._conn is None: + raise WsError("WsClient is not connected; use as a context manager") + try: + self._conn.send(json.dumps(payload)) + except Exception as exc: + raise WsProtocolError(f"WS send failed: {exc}") from exc + + def _recv(self, *, timeout_s: float | None = None) -> dict[str, Any]: + """Receive one JSON message. Raises ``WsProtocolError`` on parse failure.""" + if self._conn is None: + raise WsError("WsClient is not connected; use as a context manager") + budget = timeout_s if timeout_s is not None else self._recv_timeout_s + try: + raw = self._conn.recv(timeout=budget) + except TimeoutError as exc: + raise WsProtocolError(f"WS recv timed out after {budget:.1f}s") from exc + except Exception as exc: + raise WsProtocolError(f"WS recv failed: {exc}") from exc + if isinstance(raw, bytes): + raw = raw.decode("utf-8", errors="replace") + try: + data = json.loads(raw) + except (ValueError, TypeError) as exc: + raise WsProtocolError(f"WS reply was not valid JSON: {raw[:120]!r}") from exc + if not isinstance(data, dict): + raise WsProtocolError(f"WS reply was not a JSON object: {data!r}") + return data + + def _drain(self, *, timeout_s: float) -> list[dict[str, Any]]: + """Drain pending server-pushed messages for up to *timeout_s*. + + Used at handshake to flush the greeting batch. Per-message + timeout is short so we exit promptly when the server goes + quiet; total wall-clock budget is bounded by *timeout_s*. + """ + out: list[dict[str, Any]] = [] + deadline = time.monotonic() + timeout_s + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + try: + out.append(self._recv(timeout_s=min(0.2, remaining))) + except WsProtocolError: + # Timeout / no more messages -- normal end-of-drain. + break + return out + + def _await_typed_reply( + self, + *, + expected: set[str], + max_messages: int = 8, + ) -> dict[str, Any]: + """Drain server messages until one's ``type`` matches *expected*. + + The server interleaves push-broadcasts (``workflows_changed``, + ``keep_awake_changed``, ``github_auth_success``) with the + response to our request, so we walk the inbox up to + *max_messages* deep. ``error`` short-circuits with + ``WsProtocolError``. + """ + for _ in range(max_messages): + msg = self._recv() + t = msg.get("type") + if t == "error": + raise WsProtocolError(f"WS server returned error: {msg.get('message') or msg!r}") + if t in expected: + return msg + raise WsProtocolError( + f"WS server did not return any of {sorted(expected)} within {max_messages} messages" + ) + + # -- public API ----------------------------------------------------- + + def create_project_from_path(self, path: Path) -> ProjectCreated: + """Register *path* as a project via the App's own create flow. + + The App's handler runs full discovery: folder probe, GitHub + owner/repo detection, default-branch resolution, account + binding. We get back the resolved ``project_id``. + + ``was_created`` is best-effort: the server's + ``project_created`` reply carries a ``project`` payload but + not (currently) a "was new" flag, so we treat any successful + reply as "created or already existed -- caller should ALWAYS + emit the restart hint until upstream issue github/github-app#5483 + lands the live broadcast". The hint is suppressed once the + webview learns about the row (i.e. after the user restarts). + """ + self._send( + { + "type": "create_project_from_path", + "path": str(path), + } + ) + reply = self._await_typed_reply( + expected={"project_created", "project_updated"}, + ) + project_id, main_repo_path, was_created = _extract_project_fields( + reply, fallback_path=str(path) + ) + if not project_id: + raise WsProtocolError(f"project_created reply missing id: {reply!r}") + return ProjectCreated( + project_id=project_id, + was_created=was_created, + main_repo_path=main_repo_path or str(path), + ) + + def create_workflow( + self, + *, + name: str, + prompt: str, + interval: str = "manual", + mode: str | None = None, + schedule_hour: int = 9, + schedule_day: int = 1, + project_id: str | None = None, + enabled: bool = False, + ) -> WorkflowCreated: + """Create a workflow row through the App. + + The App generates the workflow's id (UUIDv4). ``enabled`` + defaults to ``False`` to match the install contract: APM never + flips the schedule on; the user opts in from the App UI. + """ + payload: dict[str, Any] = { + "type": "create_workflow", + "name": name, + "prompt": prompt, + "interval": interval, + "schedule_hour": schedule_hour, + "schedule_day": schedule_day, + "enabled": enabled, + } + if mode is not None: + payload["mode"] = mode + if project_id is not None: + payload["project_id"] = project_id + self._send(payload) + reply = self._await_typed_reply(expected={"workflow_created"}) + wid = _extract_workflow_id(reply) + if not wid: + raise WsProtocolError(f"workflow_created reply missing id: {reply!r}") + return WorkflowCreated(workflow_id=wid) + + def update_workflow( + self, + *, + workflow_id: str, + name: str | None = None, + prompt: str | None = None, + interval: str | None = None, + mode: str | None = None, + schedule_hour: int | None = None, + schedule_day: int | None = None, + project_id: str | None = None, + enabled: bool | None = None, + ) -> WorkflowCreated: + """Update an existing workflow row in place. + + Only fields explicitly passed are sent on the wire so the + server's partial-update semantics are preserved (unsent fields + keep their existing value). + """ + payload: dict[str, Any] = { + "type": "update_workflow", + "id": workflow_id, + } + for key, value in ( + ("name", name), + ("prompt", prompt), + ("interval", interval), + ("mode", mode), + ("schedule_hour", schedule_hour), + ("schedule_day", schedule_day), + ("project_id", project_id), + ("enabled", enabled), + ): + if value is not None: + payload[key] = value + self._send(payload) + reply = self._await_typed_reply( + expected={"workflow_updated", "workflow_created"}, + ) + wid = _extract_workflow_id(reply) or workflow_id + return WorkflowCreated(workflow_id=wid) + + +# --------------------------------------------------------------------------- +# Permissive parsers +# --------------------------------------------------------------------------- + + +def _extract_workflow_id(reply: dict[str, Any]) -> str | None: + """Pull the workflow id out of any of the shapes the server emits.""" + for key in ("id", "workflow_id"): + v = reply.get(key) + if isinstance(v, str) and v: + return v + wf = reply.get("workflow") + if isinstance(wf, dict): + v = wf.get("id") + if isinstance(v, str) and v: + return v + return None + + +def _extract_project_fields( + reply: dict[str, Any], + *, + fallback_path: str, +) -> tuple[str | None, str | None, bool]: + """Return ``(project_id, main_repo_path, was_created)`` from a project reply. + + Tolerates both ``{project: {...}}`` nested shape and top-level + fields. ``was_created`` is True when the server signalled + ``project_created`` and False when it signalled + ``project_updated`` (a HIT on existing main_repo_path). + """ + msg_type = reply.get("type", "") + was_created = msg_type == "project_created" + project_id: str | None = None + main_repo_path: str | None = None + for key in ("project_id", "id"): + v = reply.get(key) + if isinstance(v, str) and v: + project_id = v + break + proj = reply.get("project") + if isinstance(proj, dict): + if not project_id: + v = proj.get("id") + if isinstance(v, str) and v: + project_id = v + for path_key in ("main_repo_path", "path"): + pv = proj.get(path_key) + if isinstance(pv, str) and pv: + main_repo_path = pv + break + if main_repo_path is None: + for path_key in ("main_repo_path", "path"): + pv = reply.get(path_key) + if isinstance(pv, str) and pv: + main_repo_path = pv + break + return project_id, main_repo_path or fallback_path, was_created diff --git a/tests/unit/integration/test_copilot_app_ws.py b/tests/unit/integration/test_copilot_app_ws.py new file mode 100644 index 0000000000..8de7ca8759 --- /dev/null +++ b/tests/unit/integration/test_copilot_app_ws.py @@ -0,0 +1,366 @@ +"""Tests for ``copilot_app_ws``: liveness probe + WS protocol round-trip. + +We spin up a real ``websockets.sync.server`` on an ephemeral port, +write fake ``ws.{port,token}`` files into a fixture directory exposed +via the ``APM_COPILOT_APP_WS_RUN_DIR`` env override, and assert the +client speaks the App's dialect correctly. +""" + +from __future__ import annotations + +import json +import socket +import threading +import time +from collections.abc import Callable +from pathlib import Path + +import pytest + +from apm_cli.integration import copilot_app_ws as ws + +websockets = pytest.importorskip("websockets") +from websockets.sync.server import serve as _serve # noqa: E402 + +# --------------------------------------------------------------------------- +# Server harness +# --------------------------------------------------------------------------- + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class _Server: + """A throw-away ``websockets.sync`` server bound to localhost.""" + + def __init__(self, handler: Callable, *, expect_token: str | None = None): + self.port = _free_port() + self.expect_token = expect_token + self._handler = handler + self._server = None + self._thread: threading.Thread | None = None + self.connections: list[dict] = [] + + def _process_request(self, connection, request): + # Token gate via query-string (mirror the App's posture). + if self.expect_token is not None: + path = getattr(request, "path", "/") + if f"token={self.expect_token}" not in path: + from websockets.datastructures import Headers + from websockets.http11 import Response + + return Response(401, "Unauthorized", Headers(), b"bad token") + # Origin gate: must be tauri://localhost. + headers = getattr(request, "headers", {}) + origin = headers.get("Origin") if hasattr(headers, "get") else None + self.connections.append({"origin": origin, "path": getattr(request, "path", "/")}) + return None + + def _wrapped(self, websocket): + import contextlib + + with contextlib.suppress(Exception): + self._handler(websocket) + + def __enter__(self): + self._server = _serve( + self._wrapped, + "127.0.0.1", + self.port, + process_request=self._process_request, + ) + self._thread = threading.Thread(target=self._server.serve_forever, daemon=True) + self._thread.start() + # Tiny sleep so accept loop is ready when the client connects. + time.sleep(0.05) + return self + + def __exit__(self, *_): + import contextlib + + with contextlib.suppress(Exception): + self._server.shutdown() + + +@pytest.fixture +def run_dir(tmp_path: Path, monkeypatch) -> Path: + rd = tmp_path / "run" + rd.mkdir() + monkeypatch.setenv(ws._RUN_DIR_ENV, str(rd)) + return rd + + +def _write_creds(run_dir: Path, port: int, token: str) -> None: + (run_dir / "ws.port").write_text(str(port), encoding="ascii") + (run_dir / "ws.token").write_text(token, encoding="ascii") + + +# --------------------------------------------------------------------------- +# Liveness probe +# --------------------------------------------------------------------------- + + +class TestWsAvailable: + def test_no_files_returns_false(self, run_dir: Path) -> None: + assert ws.ws_available() is False + + def test_missing_token_file_returns_false(self, run_dir: Path) -> None: + (run_dir / "ws.port").write_text("12345", encoding="ascii") + assert ws.ws_available() is False + + def test_invalid_port_returns_false(self, run_dir: Path) -> None: + _write_creds(run_dir, 0, "tok") + assert ws.ws_available() is False + + def test_stale_port_no_listener_returns_false(self, run_dir: Path) -> None: + # Port file exists, but nothing is listening: probe must fail + # within the probe budget (100ms) -- we give a generous wall + # clock budget here. + _write_creds(run_dir, _free_port(), "tok") + t0 = time.monotonic() + assert ws.ws_available() is False + assert time.monotonic() - t0 < 1.0 + + def test_listener_present_returns_true(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + assert ws.ws_available() is True + + +# --------------------------------------------------------------------------- +# Handshake +# --------------------------------------------------------------------------- + + +class TestHandshake: + def test_app_not_running_raises_app_not_running(self, run_dir: Path) -> None: + # No files at all. + client = ws.WsClient() + with pytest.raises(ws.WsAppNotRunning): + client._connect() + + def test_connection_refused_raises_app_not_running(self, run_dir: Path) -> None: + _write_creds(run_dir, _free_port(), "tok") + client = ws.WsClient() + with pytest.raises(ws.WsAppNotRunning): + client._connect() + + def test_bad_token_raises_auth_error(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + + with _Server(handler, expect_token="GOOD") as srv: + _write_creds(run_dir, srv.port, "BAD") + client = ws.WsClient() + with pytest.raises(ws.WsAuthError): + client._connect() + + def test_origin_header_is_tauri_localhost(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient(): + pass + # The probe ran first then the real client connect, so + # we expect at least one connection with Origin set. + origins = [c.get("origin") for c in srv.connections] + assert "tauri://localhost" in origins + + +# --------------------------------------------------------------------------- +# Message round-trips +# --------------------------------------------------------------------------- + + +def _send_greetings(websocket) -> None: + """Push some greeting frames so the client's drain code is exercised.""" + websocket.send(json.dumps({"type": "server_hello"})) + websocket.send(json.dumps({"type": "keep_awake_changed", "enabled": False})) + + +class TestCreateProject: + def test_round_trip_returns_id_and_created_flag(self, run_dir: Path) -> None: + def handler(websocket): + _send_greetings(websocket) + raw = websocket.recv() + msg = json.loads(raw) + assert msg["type"] == "create_project_from_path" + assert msg["path"] == "/tmp/some/repo" + websocket.send( + json.dumps( + { + "type": "project_created", + "project": { + "id": "proj-uuid-1", + "main_repo_path": "/tmp/some/repo", + }, + } + ) + ) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + result = client.create_project_from_path(Path("/tmp/some/repo")) + assert result.project_id == "proj-uuid-1" + assert result.was_created is True + assert result.main_repo_path == "/tmp/some/repo" + + def test_project_updated_reply_yields_was_created_false(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send( + json.dumps( + { + "type": "project_updated", + "project": {"id": "proj-uuid-2", "main_repo_path": "/x"}, + } + ) + ) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + r = client.create_project_from_path(Path("/x")) + assert r.was_created is False + assert r.project_id == "proj-uuid-2" + + def test_server_error_raises_protocol_error(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send(json.dumps({"type": "error", "message": "no such folder"})) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + with pytest.raises(ws.WsProtocolError, match=r"no such folder"): + client.create_project_from_path(Path("/nope")) + + def test_malformed_reply_raises_protocol_error(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send("not json at all") + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + with pytest.raises(ws.WsProtocolError): + client.create_project_from_path(Path("/x")) + + def test_extra_fields_are_tolerated(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send( + json.dumps( + { + "type": "project_created", + "project": { + "id": "p-1", + "main_repo_path": "/r", + "future_field": True, + }, + "another_unknown": 42, + } + ) + ) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + r = client.create_project_from_path(Path("/r")) + assert r.project_id == "p-1" + + +class TestCreateWorkflow: + def test_round_trip_returns_id_and_omits_none_fields(self, run_dir: Path) -> None: + received: dict = {} + + def handler(websocket): + received["msg"] = json.loads(websocket.recv()) + websocket.send(json.dumps({"type": "workflow_created", "id": "wf-1"})) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + r = client.create_workflow( + name="hello", + prompt="say hi", + mode="plan", + project_id="proj-1", + ) + assert r.workflow_id == "wf-1" + msg = received["msg"] + assert msg["type"] == "create_workflow" + assert msg["name"] == "hello" + assert msg["mode"] == "plan" + assert msg["project_id"] == "proj-1" + assert msg["enabled"] is False # default + + def test_workflow_id_from_nested_workflow_object(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send(json.dumps({"type": "workflow_created", "workflow": {"id": "wf-2"}})) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + r = client.create_workflow(name="n", prompt="p") + assert r.workflow_id == "wf-2" + + +class TestUpdateWorkflow: + def test_only_set_fields_are_sent(self, run_dir: Path) -> None: + received: dict = {} + + def handler(websocket): + received["msg"] = json.loads(websocket.recv()) + websocket.send(json.dumps({"type": "workflow_updated", "id": "wf-3"})) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + client.update_workflow(workflow_id="wf-3", prompt="new") + msg = received["msg"] + assert msg["type"] == "update_workflow" + assert msg["id"] == "wf-3" + assert msg["prompt"] == "new" + # Unset fields must NOT be on the wire (partial update). + for key in ("name", "interval", "mode", "schedule_hour", "enabled"): + assert key not in msg + + +class TestDrainAndInterleavedPush: + def test_response_found_after_push_messages(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + websocket.send(json.dumps({"type": "workflows_changed"})) + websocket.send(json.dumps({"type": "github_auth_success"})) + websocket.send(json.dumps({"type": "workflow_created", "id": "wf-late"})) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient() as client: + r = client.create_workflow(name="n", prompt="p") + assert r.workflow_id == "wf-late" + + +class TestRecvTimeout: + def test_recv_timeout_raises_protocol_error(self, run_dir: Path) -> None: + def handler(websocket): + websocket.recv() + # Never reply -- client must time out. + time.sleep(2.0) + + with _Server(handler) as srv: + _write_creds(run_dir, srv.port, "tok") + with ws.WsClient(recv_timeout_s=0.3) as client: + with pytest.raises(ws.WsProtocolError, match=r"timed out"): + client.create_workflow(name="n", prompt="p") From 3defbbb2d03f0c8297278cdc9d54e1004e356611 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:15 +0200 Subject: [PATCH 04/10] feat(copilot-app): stamp project_id on every workflow row Adds project_id: str | None to WorkflowRow and threads it through both INSERT and UPDATE paths in deploy_workflow. The execution-changed UPDATE includes project_id alongside the other execution fields; the name-only UPDATE also writes project_id so pre-PR-A rows with NULL project_id self-heal on the next install without forcing a content change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/integration/copilot_app_db.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/apm_cli/integration/copilot_app_db.py b/src/apm_cli/integration/copilot_app_db.py index 3291ea31f8..75b77d55b4 100644 --- a/src/apm_cli/integration/copilot_app_db.py +++ b/src/apm_cli/integration/copilot_app_db.py @@ -270,9 +270,11 @@ def is_copilot_app_uri(lockfile_path: str) -> bool: class WorkflowRow: """Subset of the ``workflows`` table columns APM writes. - Fields not listed here (``created_at``, ``updated_at``, ``project_id``, + Fields not listed here (``created_at``, ``updated_at``, ``last_run_at``, ``next_run_at``) are left to the database defaults - or to existing values when updating. + or to existing values when updating. ``project_id`` is now first- + class on the write path (PR A) so every APM-installed workflow row + is scoped to a real ``projects`` row. """ id: str @@ -285,6 +287,7 @@ class WorkflowRow: model: str | None = None reasoning_effort: str | None = None mode: str | None = None + project_id: str | None = None def _connect(db_path: Path) -> sqlite3.Connection: @@ -453,8 +456,8 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: INSERT INTO workflows ( id, name, prompt, model, reasoning_effort, interval, schedule_hour, schedule_day, - enabled, mode - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?) + enabled, mode, project_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?) """, ( row.id, @@ -466,6 +469,7 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: row.schedule_hour, row.schedule_day, row.mode, + row.project_id, ), ) else: @@ -490,6 +494,7 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: schedule_hour = ?, schedule_day = ?, mode = ?, + project_id = ?, enabled = 0, next_run_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') @@ -504,18 +509,23 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: row.schedule_hour, row.schedule_day, row.mode, + row.project_id, row.id, ), ) else: + # Self-heal pre-PR-A rows: even when nothing else + # changed, stamp project_id so a NULL left by an + # older APM install is filled on the next run. conn.execute( """ UPDATE workflows SET name = ?, + project_id = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ? """, - (row.name, row.id), + (row.name, row.project_id, row.id), ) conn.execute("COMMIT") except Exception: From bf190db4c955ba42690b60b85f2ba941bb2fcbf5 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:35 +0200 Subject: [PATCH 05/10] feat(copilot-app): hybrid WS+SQLite dispatch with project scoping prompt_integrator.integrate_prompts_for_target now accepts scope= and forwards user-scope detection to _integrate_prompts_for_copilot_app, which: 1. Parses all candidate workflow-shape prompts up front so the path decision (WS / SQLite / global-warn) is made once per package. 2. Emits a warn-and-proceed diagnostic when --global is combined with workflow-shape prompts, explaining that those workflows will run with CWD=~/.copilot and pointing at the App's Workflows tab to attach them to a project manually. 3. Derives a RepoContext from project_root; when the App is running AND we have a real repo, tries the WS-IPC path first (create_project_from_path + per-workflow create_workflow). On any WsError, warns and falls back to SQLite. 4. SQLite fallback: resolve_or_register_project_sqlite, stamp project_id on every WorkflowRow, suffix display name with ' ()' so workflows from different repos are distinguishable in the App UI. 5. When the project row was freshly created (was_created=True), emits a one-time restart-the-App info diagnostic referencing the upstream live-refresh gap (github/github-app#5483). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/integration/prompt_integrator.py | 236 ++++++++++++++++++- 1 file changed, 224 insertions(+), 12 deletions(-) diff --git a/src/apm_cli/integration/prompt_integrator.py b/src/apm_cli/integration/prompt_integrator.py index bbaa1ed655..591155112b 100644 --- a/src/apm_cli/integration/prompt_integrator.py +++ b/src/apm_cli/integration/prompt_integrator.py @@ -74,19 +74,28 @@ def integrate_prompts_for_target( force: bool = False, managed_files: set[str] | None = None, diagnostics=None, + scope=None, ) -> IntegrationResult: """Integrate prompts for a single *target*.""" mapping = target.primitives.get("prompts") if not mapping: return IntegrationResult(0, 0, 0, []) - # GitHub Copilot desktop App: deploy to SQLite instead of files. - # The branch fully owns lifecycle for this target -- it does not - # share the file-based collision / link-resolution machinery. + # GitHub Copilot desktop App: deploy to SQLite (or WS-IPC when + # the App is running) instead of files. The branch fully owns + # lifecycle for this target -- it does not share the file-based + # collision / link-resolution machinery. if target.name == "copilot-app": + # Detect --global / user-scope by name; we accept either the + # InstallScope enum or a string. Avoids a hard import cycle. + user_scope = False + if scope is not None: + user_scope = getattr(scope, "name", str(scope)).upper() == "USER" return self._integrate_prompts_for_copilot_app( target, package_info, + project_root=project_root, + user_scope=user_scope, force=force, diagnostics=diagnostics, ) @@ -138,11 +147,35 @@ def _integrate_prompts_for_copilot_app( target: TargetProfile, package_info, *, + project_root: Path, + user_scope: bool, force: bool, diagnostics, ) -> IntegrationResult: """Deploy workflow-shape prompts as Copilot App workflow rows. + Hybrid dispatch (PR A): + + 1. Detect the repo at ``project_root``. Derive a stable + ``ProjectRecipe`` (id, name, github owner/repo, default + branch) so the workflow rows can be scoped to a real + ``projects`` row instead of orphaned at the root. + 2. If ``user_scope`` is set AND any workflow-shape prompts are + present, emit a warn-and-proceed diagnostic: workflows run + with CWD=~/.copilot in global mode, which is almost never + what the user wants. We still deploy so global skills / + commands keep working; the user can attach the row to a + project from the App UI. + 3. If the App is running (``ws_available``), try the WS-IPC + path: ``create_project_from_path`` then ``create_workflow`` + per prompt. The App generates UUIDs; we do not control the + row id but we get the live ``WorkflowsChanged`` broadcast + and avoid the project-not-loaded white-screen failure mode. + 4. Otherwise (or on any WS error), fall back to the direct + SQLite path: register / look up the project via + ``resolve_or_register_project_sqlite``, stamp ``project_id`` + on every row, and suffix the display name with ``()``. + Workflow-shape (per ``_is_workflow_shape``) prompts deploy here. Plain-shape prompts (no execution-affecting frontmatter keys) are a hard error at this target: the user explicitly opted into @@ -165,6 +198,14 @@ def _integrate_prompts_for_copilot_app( namespaced_id, resolve_copilot_app_db_path, ) + from apm_cli.integration.copilot_app_project import ( + derive_repo_context, + resolve_or_register_project_sqlite, + ) + from apm_cli.integration.copilot_app_ws import ( + WsError, + ws_available, + ) db_path = resolve_copilot_app_db_path() if db_path is None: @@ -173,11 +214,12 @@ def _integrate_prompts_for_copilot_app( owner = _derive_package_owner(package_info) pkg_name = package_info.package.name - files_integrated = 0 + # ------------------------------------------------------------------ + # Parse all candidate prompts up front so we can decide on the + # WS path / SQLite path / global-scope warning with one pass. + # ------------------------------------------------------------------ + parsed: list[tuple[Path, object, object]] = [] files_skipped = 0 - target_paths: list[Path] = [] - synthetic_root = db_path.parent / "workflows" - for source_file in self.find_prompt_files(package_info.install_path): if source_file.is_symlink(): if diagnostics is not None: @@ -189,10 +231,6 @@ def _integrate_prompts_for_copilot_app( continue post = frontmatter.load(str(source_file)) if not _is_workflow_shape(post.metadata): - # Plain prompt at copilot-app target -- hard error. - # Authors who want a workflow add an execution-shape - # key (e.g. ``interval: manual``); a plain prompt has - # no business in the App's workflows table. if diagnostics is not None: diagnostics.warn( message=( @@ -215,9 +253,98 @@ def _integrate_prompts_for_copilot_app( ) files_skipped += 1 continue + parsed.append((source_file, post, schedule)) + + # ------------------------------------------------------------------ + # --global + workflow-shape: warn but proceed. + # ------------------------------------------------------------------ + if user_scope and parsed and diagnostics is not None: + diagnostics.warn( + message=( + "Copilot App workflows installed with --global run with CWD=~/.copilot, " + "not a project. Attach the workflow to a project from the App's Workflows " + "tab to fix this, or re-run `apm install` from a repo without --global. " + "See https://aka.ms/apm/copilot-app-global for details." + ), + package=pkg_name, + ) + + # ------------------------------------------------------------------ + # Project scoping. + # ------------------------------------------------------------------ + repo_ctx = derive_repo_context(project_root) + repo_suffix = f" ({repo_ctx.repo_name})" if repo_ctx is not None else "" + + # WS path -- preferred when the App is running. We try it ONLY + # when we have a real repo context (a project to attach the + # workflows to); otherwise the WS path adds no value over the + # SQLite fallback. + if repo_ctx is not None and ws_available(): + try: + return self._deploy_via_ws( + repo_ctx=repo_ctx, + parsed=parsed, + pkg_name=pkg_name, + owner=owner, + files_skipped=files_skipped, + diagnostics=diagnostics, + db_path=db_path, + ) + except WsError as exc: + # Live App but WS path broke -- log and fall through to + # SQLite. We never let a transient WS failure turn into + # a hard install error. + if diagnostics is not None: + diagnostics.warn( + message=( + f"Copilot App live IPC unavailable ({exc}); " + "falling back to direct database write." + ), + package=pkg_name, + ) + + # ------------------------------------------------------------------ + # SQLite fallback path. + # ------------------------------------------------------------------ + project_id: str | None = None + was_created = False + if repo_ctx is not None: + try: + resolved = resolve_or_register_project_sqlite(db_path, repo_ctx) + project_id = resolved.project_id + was_created = resolved.was_created + except CopilotAppDbError as exc: + if diagnostics is not None: + diagnostics.warn( + message=( + f"Could not register project for Copilot App: {exc}. " + "Workflows will be installed without a project binding." + ), + package=pkg_name, + ) + + if was_created and diagnostics is not None: + # See github/github-app#5483 -- the App webview does not + # currently refresh on externally-inserted ``projects`` + # rows. A one-time restart wires the new project into the + # UI; subsequent installs into the same repo are silent. + diagnostics.info( + message=( + "Registered a new Copilot App project for this repo. " + "Restart the Copilot App once so the new project appears in the UI " + "(see github/github-app#5483)." + ), + package=pkg_name, + ) + + synthetic_root = db_path.parent / "workflows" + files_integrated = 0 + target_paths: list[Path] = [] + for source_file, post, schedule in parsed: prompt_stem = source_file.name.removesuffix(".prompt.md") wf_id = namespaced_id(owner, pkg_name, prompt_stem) - display_name = post.metadata.get("name") or prompt_stem + base_name = post.metadata.get("name") or prompt_stem + display_name = f"{base_name}{repo_suffix}" row = WorkflowRow( id=wf_id, name=str(display_name), @@ -229,6 +356,7 @@ def _integrate_prompts_for_copilot_app( model=schedule.model, reasoning_effort=schedule.reasoning_effort, mode=schedule.mode, + project_id=project_id, ) try: deploy_workflow(db_path, row) @@ -252,6 +380,90 @@ def _integrate_prompts_for_copilot_app( files_adopted=0, ) + def _deploy_via_ws( + self, + *, + repo_ctx, + parsed: list, + pkg_name: str, + owner: str, + files_skipped: int, + diagnostics, + db_path: Path, + ) -> IntegrationResult: + """Deploy workflow rows through the live App's WS-IPC surface. + + The App generates its own UUIDs for both the project and each + workflow; we do NOT use ``namespaced_id`` here. Lockfile + bookkeeping still uses the same ``copilot-app-db://workflows/`` + scheme so uninstall + sync stays consistent regardless of which + path created the row -- the id is opaque to the rest of APM. + """ + from apm_cli.integration.copilot_app_db import ( + WorkflowRow, + deploy_workflow, + namespaced_id, + ) + from apm_cli.integration.copilot_app_ws import WsClient + + repo_suffix = f" ({repo_ctx.repo_name})" + synthetic_root = db_path.parent / "workflows" + files_integrated = 0 + target_paths: list[Path] = [] + + with WsClient() as client: + try: + project = client.create_project_from_path(repo_ctx.repo_root) + except Exception: + raise + + if project.was_created and diagnostics is not None: + diagnostics.info( + message=( + "Registered a new Copilot App project for this repo. " + "If the Workflows tab does not refresh, restart the App once " + "(see github/github-app#5483)." + ), + package=pkg_name, + ) + + # The App generates row UUIDs server-side, but we ALSO write + # a namespaced row via the SQLite path so the lockfile keeps + # a stable, predictable id. We do the SQLite write here + # (same db_path the App opens) -- the App's row and ours + # coexist; uninstall removes ours by id. This avoids the + # "WS path breaks namespacing" problem flagged in the plan. + for source_file, post, schedule in parsed: + prompt_stem = source_file.name.removesuffix(".prompt.md") + wf_id = namespaced_id(owner, pkg_name, prompt_stem) + base_name = post.metadata.get("name") or prompt_stem + display_name = f"{base_name}{repo_suffix}" + row = WorkflowRow( + id=wf_id, + name=str(display_name), + prompt=post.content, + interval=schedule.interval, + schedule_hour=schedule.schedule_hour, + schedule_day=schedule.schedule_day, + enabled=0, + model=schedule.model, + reasoning_effort=schedule.reasoning_effort, + mode=schedule.mode, + project_id=project.project_id, + ) + deploy_workflow(db_path, row) + files_integrated += 1 + target_paths.append(synthetic_root / wf_id) + + return IntegrationResult( + files_integrated=files_integrated, + files_updated=0, + files_skipped=files_skipped, + target_paths=target_paths, + links_resolved=0, + files_adopted=0, + ) + def _sync_copilot_app(self, managed_files: set[str]) -> dict[str, int]: """Remove Copilot App workflow rows referenced by *managed_files*. From 6030a88b0001374250da44dea2f0866b652fcb1a Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:36 +0200 Subject: [PATCH 06/10] feat(install): thread scope into integrator dispatch services.py now passes scope= to integrate_*_for_target so the prompt integrator can distinguish project-scope from user-scope at the copilot-app branch. The four sibling integrators (agent, command, hook, instruction) accept scope= as a keyword-only no-op default to keep the call site uniform without changing their behavior. Also refreshes the copilot-app explainer in phases/targets.py to document the PR A auto-register + restart-once UX. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/install/phases/targets.py | 13 +++++++++++++ src/apm_cli/install/services.py | 1 + src/apm_cli/integration/agent_integrator.py | 1 + src/apm_cli/integration/command_integrator.py | 1 + src/apm_cli/integration/hook_integrator.py | 1 + src/apm_cli/integration/instruction_integrator.py | 1 + 6 files changed, 18 insertions(+) diff --git a/src/apm_cli/install/phases/targets.py b/src/apm_cli/install/phases/targets.py index 7a9d82c260..b4fbe4e1c0 100644 --- a/src/apm_cli/install/phases/targets.py +++ b/src/apm_cli/install/phases/targets.py @@ -257,6 +257,19 @@ def run(ctx: InstallContext) -> None: # prevents collisions across projects sharing the same package. # Rows always arrive enabled=0; users grant the second consent in # the App's Workflows tab before anything runs on a schedule. + # + # PR A (project-scoping): the integrator now auto-registers a row + # in the App's ``projects`` table for the current repository and + # stamps every workflow with that project_id, so workflows show up + # in the correct project's Workflows tab. On the *first* install + # into a repo, the App's webview does not always live-refresh on + # the externally-inserted ``projects`` row (see github/github-app + # #5483); the integrator emits a one-time restart hint so the user + # is not left wondering why the new project is missing from the UI. + # When the App is running, the integrator prefers the live + # WebSocket-IPC surface so the broadcast fires natively and no + # restart is needed; the SQLite path is the fallback for the + # App-closed case (still the common case during install). # ------------------------------------------------------------------ # v2 resolution (#1154): signal-based provenance and strict errors. diff --git a/src/apm_cli/install/services.py b/src/apm_cli/install/services.py index d373063622..25204a3d40 100644 --- a/src/apm_cli/install/services.py +++ b/src/apm_cli/install/services.py @@ -272,6 +272,7 @@ def _format_target_collapse(paths: list[str], verbose: bool) -> tuple[str, list[ force=force, managed_files=managed_files, diagnostics=diagnostics, + scope=scope, ) result["links_resolved"] += _int_result.links_resolved for tp in _int_result.target_paths: diff --git a/src/apm_cli/integration/agent_integrator.py b/src/apm_cli/integration/agent_integrator.py index a005193ff2..55f1b4649d 100644 --- a/src/apm_cli/integration/agent_integrator.py +++ b/src/apm_cli/integration/agent_integrator.py @@ -94,6 +94,7 @@ def integrate_agents_for_target( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + scope=None, ) -> IntegrationResult: """Integrate agents from a package for a single *target*. diff --git a/src/apm_cli/integration/command_integrator.py b/src/apm_cli/integration/command_integrator.py index 0b12777619..f30604aa33 100644 --- a/src/apm_cli/integration/command_integrator.py +++ b/src/apm_cli/integration/command_integrator.py @@ -455,6 +455,7 @@ def integrate_commands_for_target( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + scope=None, ) -> IntegrationResult: """Integrate prompt files as commands for a single *target*. diff --git a/src/apm_cli/integration/hook_integrator.py b/src/apm_cli/integration/hook_integrator.py index 4c8272d880..b29705c1c0 100644 --- a/src/apm_cli/integration/hook_integrator.py +++ b/src/apm_cli/integration/hook_integrator.py @@ -1033,6 +1033,7 @@ def integrate_hooks_for_target( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + scope=None, ) -> "HookIntegrationResult": """Integrate hooks for a single *target*. diff --git a/src/apm_cli/integration/instruction_integrator.py b/src/apm_cli/integration/instruction_integrator.py index e4a5118c12..12b1fa5cb1 100644 --- a/src/apm_cli/integration/instruction_integrator.py +++ b/src/apm_cli/integration/instruction_integrator.py @@ -66,6 +66,7 @@ def integrate_instructions_for_target( force: bool = False, managed_files: set[str] | None = None, diagnostics=None, + scope=None, ) -> IntegrationResult: """Integrate instructions for a single *target*. From 82aebc2c3282958b7a8a75eb0930991a17515df9 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 16:42:36 +0200 Subject: [PATCH 07/10] test(copilot-app): cover project_id stamping, restart hint, global warn - Extends the seed schema fixture with a projects table so the resolver can run end-to-end. - Asserts on the project-scope roundtrip that the workflow row carries a non-NULL project_id pointing at a projects row with main_repo_path equal to the consumer directory, and that the display name carries the '()' suffix. - git init's the consumer directory so derive_repo_context returns a real RepoContext. - Asserts the restart-the-App hint is emitted on the first install into a new repo. - New test_global_install_with_workflow_emits_warning: --global plus workflow-shape prompts warn-and-proceeds (exit 0, row inserted, warning mentions --global + 'attach') instead of the prior hard-fail. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../test_install_target_copilot_app_e2e.py | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/tests/unit/install/test_install_target_copilot_app_e2e.py b/tests/unit/install/test_install_target_copilot_app_e2e.py index e97ca91477..21e38411d0 100644 --- a/tests/unit/install/test_install_target_copilot_app_e2e.py +++ b/tests/unit/install/test_install_target_copilot_app_e2e.py @@ -29,6 +29,20 @@ _BASE_ENV: dict[str, str] = {"APM_E2E_TESTS": "1"} _WORKFLOWS_SCHEMA = """ +CREATE TABLE IF NOT EXISTS "projects" ( + id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + container_kind TEXT NOT NULL DEFAULT 'repository', + main_repo_path TEXT UNIQUE, + default_branch TEXT, + github_owner TEXT, + github_repo TEXT, + auto_open_in_browser INTEGER NOT NULL DEFAULT 1, + auto_approve INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) +); + CREATE TABLE IF NOT EXISTS "workflows" ( id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, @@ -415,8 +429,17 @@ def test_install_project_scope_then_uninstall_deletes_db_row( # Project consumer lives in a separate directory; CliRunner runs # in cwd, so we change into it for the install + uninstall calls. + # ``git init`` so derive_repo_context can build a RepoContext and + # the integrator stamps a real project_id (PR A). + import subprocess as _sp + consumer_dir = tmp_path / "consumer-project" consumer_dir.mkdir() + _sp.run( + ["git", "init", "-q", str(consumer_dir)], + check=True, + capture_output=True, + ) (consumer_dir / "apm.yml").write_text(_MINIMAL_APM_YML, encoding="ascii") monkeypatch.chdir(consumer_dir) @@ -450,6 +473,35 @@ def test_install_project_scope_then_uninstall_deletes_db_row( ) assert ids_after_install[0].startswith("apm--"), ids_after_install[0] + # PR A: project-scope installs MUST stamp project_id on the + # workflow row so it shows up under the correct project in the + # App's Workflows tab. The integrator auto-registers a row in + # the ``projects`` table for the consumer directory. + conn = sqlite3.connect(str(db)) + try: + row = conn.execute( + "SELECT project_id, name FROM workflows WHERE id = ?", + (ids_after_install[0],), + ).fetchone() + assert row is not None + assert row[0] is not None, "project_id must be stamped on the workflow row" + # Display name carries the repo suffix `()`. + assert "(" in row[1] and ")" in row[1], ( + f"workflow name should have repo suffix, got {row[1]!r}" + ) + proj = conn.execute( + "SELECT main_repo_path FROM projects WHERE id = ?", (row[0],) + ).fetchone() + assert proj is not None + assert Path(proj[0]) == consumer_dir.resolve() + finally: + conn.close() + + # First-time install into a new repo must emit the restart hint + # (the App webview does not live-refresh on externally-inserted + # projects rows -- see github/github-app#5483). + assert "Restart the Copilot" in install_result.output, install_result.output + uninstall_result = runner.invoke( cli, ["uninstall", str(pkg_dir), "-v"], @@ -472,3 +524,73 @@ def test_install_project_scope_then_uninstall_deletes_db_row( f"--- uninstall output ---\n{uninstall_result.output}\n" f"--- post-uninstall lockfile ---\n{_lock}\n" ) + + def test_global_install_with_workflow_emits_warning( + self, + tmp_path: Path, + fake_home: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """``--global`` + workflow-shape prompts warns (not fails). + + Workflows installed at user scope run with CWD=~/.copilot, not a + project, which is almost never what the author intended. PR A + replaces the prior hard-fail with a warn-and-proceed: the row + still lands, but the user is told to attach it to a project + from the App UI. + """ + import apm_cli.config as _conf + + monkeypatch.setattr( + _conf, + "_config_cache", + {"experimental": {"copilot_app": True}}, + ) + db = _seed_db(fake_home / "data.db") + monkeypatch.setenv("APM_COPILOT_APP_DB", str(db)) + + pkg_dir = tmp_path / "global-wf-pkg" + prompts_dir = pkg_dir / ".apm" / "prompts" + prompts_dir.mkdir(parents=True) + (pkg_dir / "apm.yml").write_text( + textwrap.dedent( + """\ + name: global-wf-pkg + description: global+workflow warn test + version: 0.0.1 + """ + ), + encoding="ascii", + ) + (prompts_dir / "morning.prompt.md").write_text( + textwrap.dedent( + """\ + --- + name: Morning + interval: daily + schedule_hour: 8 + schedule_day: 1 + --- + Greet the day. + """ + ), + encoding="ascii", + ) + + from apm_cli.integration import copilot_app_db as cdb + + runner = CliRunner() + result = runner.invoke( + cli, + ["install", str(pkg_dir), "--target", "copilot-app", "--global"], + env={**_BASE_ENV, "APM_COPILOT_APP_DB": str(db)}, + catch_exceptions=False, + ) + # Warn-and-proceed: exit 0, row was inserted, but warning visible. + assert result.exit_code == 0, result.output + ids = cdb.list_managed_workflow_ids(db) + assert len(ids) == 1, ids + # Warning text must mention --global and surface the attach hint. + out = (result.output or "").lower() + assert "--global" in out, result.output + assert "attach" in out, result.output From 75688f7b026f10f8375b660ee6295fa920649ce4 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 17:23:54 +0200 Subject: [PATCH 08/10] fix(copilot-app): address panel follow-ups on PR #1431 Path B narrow WS surface (project-registration only), token hardening, fallback regression test, and doc/PR-body honesty pass. Source: - copilot_app_ws.py: delete create_workflow/update_workflow/ WorkflowCreated/_extract_workflow_id; add _scrub_token regex that redacts ?token=... in wrapped exception text; add _token_file_mode_ok check refusing ws.token if group/other-readable (matches App's 0o600 posture); raise WsError from None so library exceptions with the unscrubbed URL are not reachable via __context__. - prompt_integrator.py: rewrite _integrate_prompts_for_copilot_app as a single-loop dispatcher. Resolve project_id once (try WS, fall back to SQLite on WsError; silently swallow WsAppNotRunning and WsAuthError so stale tokens after a restart never warn). Write every workflow row via SQLite with the resolved project_id. One restart- once hint when was_created. Drop the WS/IPC jargon from user-facing wording. Delete _deploy_via_ws. - pyproject.toml + uv.lock: pin websockets>=12,<17. Tests: - tests/unit/integration/test_copilot_app_ws.py: drop TestCreateWorkflow + TestUpdateWorkflow; port TestDrainAndInterleavedPush and TestRecvTimeout onto create_project_from_path; chmod 0o600 in the _write_creds fixture so the new mode check passes; add TestTokenScrub (3) and TestTokenFileMode (3). - tests/integration/test_copilot_app_ws_fallback.py (new): regression trap for WS-error -> SQLite fallback. WsProtocolError mid-deploy still stamps project_id on the workflow row; WsAppNotRunning and WsAuthError stay silent. Docs: - CHANGELOG.md: corrected Unreleased entries (Added/Security). - docs/.../integrations/copilot-app.md: Project scoping + One-time restart hint + --global warn-and-proceed sections. - packages/apm-guide/.apm/skills/apm-usage/commands.md: project-scope + restart-hint + --global warn callouts in the experimental section. PR body: rewritten to drop misleading mode-allowlist bullet and the 'live workflows_changed broadcast' framing; sequence diagram now shows WS for project registration and SQLite for workflow rows; scenario table extended with WS-fallback and token-hardening evidence. Validation: ruff check + format --check silent; 2766 unit integration+install tests pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 10 + .../content/docs/integrations/copilot-app.md | 35 +++ .../.apm/skills/apm-usage/commands.md | 2 +- pyproject.toml | 2 +- src/apm_cli/integration/copilot_app_ws.py | 223 ++++++-------- src/apm_cli/integration/prompt_integrator.py | 233 +++++--------- .../test_copilot_app_ws_fallback.py | 290 ++++++++++++++++++ tests/unit/integration/test_copilot_app_ws.py | 164 ++++++---- uv.lock | 2 +- 9 files changed, 609 insertions(+), 352 deletions(-) create mode 100644 tests/integration/test_copilot_app_ws_fallback.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f6743eda6e..d7615725b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Experimental:** `copilot-app` target now scopes workflow rows to a real `projects` row instead of orphaning them at the App's root. When the App is running, project registration goes through the loopback WebSocket IPC surface (`~/.copilot/run/ws.{port,token}`, 0o600) so the project goes through the App's own owner/repo discovery and is immediately known to the webview; when the App is closed, registration falls through to a direct-SQLite `BEGIN IMMEDIATE` resolver against `~/.copilot/data.db`. Workflow rows are always written via SQLite (namespaced ids preserve lockfile stability). `--global` installs that carry workflow-shape prompts now emit a one-time warn-and-proceed diagnostic explaining the CWD-pivot risk and the per-row "attach to project" remediation. A one-time `Restart the Copilot App once` info hint fires on first project registration in a repo (see github/github-app#5483). (#1431) + ### Changed - Unit test coverage raised to 88% (gate: `fail_under = 80`); integration test coverage raised to 71% with first CI gate at 55%. (#1402) +### Security + +- `copilot-app` WS client refuses to read `~/.copilot/run/ws.token` if its mode is group- or other-readable, matching the App's documented 0o600 posture. Library exception text that echoes the handshake URL is scrubbed of any `?token=...` query argument before being wrapped into `WsError` subtypes, so credential material cannot land in diagnostics or user-visible warnings. (#1431) +- `websockets` dependency is pinned with an upper bound (`>=12,<17`) to lock the current resolution and prevent a future major-version upload from silently landing across user installs. (#1431) + + ## [0.14.1] - 2026-05-20 ### Added diff --git a/docs/src/content/docs/integrations/copilot-app.md b/docs/src/content/docs/integrations/copilot-app.md index 7c46e80afc..96f287cd90 100644 --- a/docs/src/content/docs/integrations/copilot-app.md +++ b/docs/src/content/docs/integrations/copilot-app.md @@ -78,6 +78,41 @@ Execution-affecting fields are the prompt body, schedule (`interval` / `schedule Removing the source `.prompt.md` from a package and re-syncing drops the lockfile entry but does NOT delete the corresponding row from `~/.copilot/data.db` -- it merely orphans it. Run `apm uninstall ` to remove the row. +## Project scoping + +Workflows are scoped to a real Copilot App project so "Run now" in the Workflows tab CWDs into the right repository and the row groups under the correct sidebar entry. APM resolves the project once per install, then stamps every workflow row's `project_id`. + +Two resolution paths run in this order: + +| Order | When it fires | What it does | +|---|---|---| +| 1 | The Copilot App is running and is reachable on its loopback WebSocket (`~/.copilot/run/ws.{port,token}`, 0o600). | APM calls the App's own `create_project_from_path` over IPC. The App runs full discovery (GitHub owner/repo detection, default branch, account binding) and the resulting project is immediately known to the webview, so opening the Workflows tab cannot hit the white-screen-on-unknown-project failure mode. | +| 2 | The Copilot App is closed, OR the WebSocket surface is unreachable for any reason (stale token after restart, etc). | APM falls back to a direct-SQLite `BEGIN IMMEDIATE` resolver: SELECT by `main_repo_path` (UNIQUE), INSERT if missing. | + +In both paths the workflow rows are written via direct SQLite -- the WS surface is currently project-registration only -- so lockfile ids stay namespaced and stable (`apm------`) across runs and across the WS-vs-SQLite branch. + +If APM cannot derive a repo context at all (no `.git/`, no `origin`, etc) the workflows install with `project_id = NULL`. You can attach them to any project after the fact from the App's Workflows tab. + +### One-time restart hint + +The first time APM registers a brand-new project for a given repository, install prints: + +``` +[i] Registered a new Copilot App project for this repo. Restart the Copilot App once so the new project appears in the UI (see github/github-app#5483). +``` + +Subsequent installs into the same repo are silent. The hint is upstream-bug guidance: the App's webview does not currently refresh its projects sidebar when a new `projects` row appears mid-session, so one restart wires the new project into the UI. Once the App learns about the project, neither the install nor the App needs to be restarted again. + +## `--global` and workflow-shape prompts + +Workflows installed with `apm install --global` run with `CWD=~/.copilot`, not a repository -- which is almost never what the user wants. APM still deploys global workflows (so global skills and commands keep working), but emits a one-time warn-and-proceed diagnostic whenever a `--global` install carries any workflow-shape prompt: + +``` +[!] Copilot App workflows installed with --global run with CWD=~/.copilot, not a project. Attach the workflow to a project from the App's Workflows tab to fix this, or re-run `apm install` from a repo without --global. +``` + +The remediation is per-row: attach the workflow to any project from the Workflows tab in the App. Or re-run `apm install` from inside a repo without `--global`. + ## Enable and check Use `apm experimental enable copilot-app` to turn the target on, `apm experimental list` to see all flags, and `apm experimental disable copilot-app` to turn it off again. See the [Experimental flags reference](../../reference/experimental/) for the complete subcommand surface. diff --git a/packages/apm-guide/.apm/skills/apm-usage/commands.md b/packages/apm-guide/.apm/skills/apm-usage/commands.md index 03049b102a..3b36e563b3 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/commands.md +++ b/packages/apm-guide/.apm/skills/apm-usage/commands.md @@ -141,7 +141,7 @@ Set `MCP_REGISTRY_URL` (default `https://api.mcp.github.com`) to point all `apm Use `apm experimental enable copilot-cowork` to turn on Microsoft 365 Copilot Cowork skill deployment. Once enabled, deploy skills with `apm install --target copilot-cowork --global`. -Use `apm experimental enable copilot-app` to turn on GitHub Copilot desktop App workflow deployment. Once enabled, prompts that carry workflow frontmatter -- any flat top-level key of `interval`, `schedule_hour`, `schedule_day` -- can be deployed to the App's SQLite store at `~/.copilot/data.db` with `apm install --target copilot-app` (project scope) or `--target copilot-app --global` (user scope). A `.prompt.md` belongs to exactly ONE surface: workflow-shape prompts go to the App DB, plain prompts go to slash-command targets. Rows always start `enabled = 0` -- you opt in from the App. `apm install / update / uninstall` preserve user state (`enabled`, `last_run_at`, schedule overrides). Override the database path with `APM_COPILOT_APP_DB=`. +Use `apm experimental enable copilot-app` to turn on GitHub Copilot desktop App workflow deployment. Once enabled, prompts that carry workflow frontmatter -- any flat top-level key of `interval`, `schedule_hour`, `schedule_day` -- can be deployed to the App's SQLite store at `~/.copilot/data.db` with `apm install --target copilot-app` (project scope) or `--target copilot-app --global` (user scope). A `.prompt.md` belongs to exactly ONE surface: workflow-shape prompts go to the App DB, plain prompts go to slash-command targets. Rows always start `enabled = 0` -- you opt in from the App. `apm install / update / uninstall` preserve user state (`enabled`, `last_run_at`, schedule overrides). Override the database path with `APM_COPILOT_APP_DB=`. Workflows are scoped to a real Copilot App project: when the App is running APM registers the project over the App's loopback WebSocket so the project is immediately known to the webview; when the App is closed APM falls back to a direct-SQLite `BEGIN IMMEDIATE` resolver. The first install in a brand-new repo prints a one-time "restart the Copilot App once" hint (see github/github-app#5483); subsequent installs are silent. `--global` installs that carry workflow-shape prompts warn-and-proceed because workflows run with `CWD=~/.copilot` rather than a repo -- attach the row to a project from the App's Workflows tab to fix. ### Cross-client skills (`agent-skills`) diff --git a/pyproject.toml b/pyproject.toml index 46c683bea2..c0f5994784 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,7 @@ dependencies = [ "GitPython>=3.1.0", "ruamel.yaml>=0.18.0", "filelock>=3.12", - "websockets>=12", + "websockets>=12,<17", ] [project.optional-dependencies] diff --git a/src/apm_cli/integration/copilot_app_ws.py b/src/apm_cli/integration/copilot_app_ws.py index 7236a5ac29..eb0c27c344 100644 --- a/src/apm_cli/integration/copilot_app_ws.py +++ b/src/apm_cli/integration/copilot_app_ws.py @@ -2,21 +2,27 @@ The App binds a per-launch authenticated WebSocket on ``127.0.0.1:`` and writes the port and token to ``~/.copilot/run/ws.{port,token}`` -(mode 0o600). Any local process that can read those files can speak -the full ``WsClientMessage`` dialect. This module is the typed, -synchronous, scope-limited Python client APM uses to: - -* register a project from a filesystem path (``create_project_from_path``), -* create or update an APM-managed workflow row attached to that - project (``create_workflow`` / ``update_workflow``). - -The WS path is the **preferred** integration surface when the App is -running: it goes through the App's own validation, fires the global -``WorkflowsChanged`` broadcast so the Workflows tab live-refreshes, -and avoids the white-screen failure mode where the webview cannot -resolve an externally-written ``project_id`` (see reverse-eng report). -When the App is closed the WS surface is unavailable and the caller -falls back to direct SQLite via ``copilot_app_project``. +(mode 0o600 -- we re-check the token file's mode at read time and +refuse to use a group/other-readable token). Any local process that +can read those files can speak the full ``WsClientMessage`` dialect. +This module is the typed, synchronous, scope-limited Python client APM +uses to register a project from a filesystem path +(``create_project_from_path``). + +Scope: project registration only. + +Workflow rows are written via direct SQLite in +``copilot_app_db.deploy_workflow`` regardless of which path created the +project. This keeps lockfile ids stable (namespaced +``owner/pkg/stem``) instead of opaque server-side UUIDs, and removes +the need for paired ``create_workflow`` / ``update_workflow`` IPC. The +WS surface still earns its keep on the project side: the App runs full +discovery (owner/repo detection, default branch, account binding) and +the resulting project row is the one the webview already knows about, +which is how we avoid the white-screen failure mode where an +externally-written ``project_id`` doesn't resolve. When the App is +closed the WS surface is unavailable and the caller falls back to +direct SQLite project registration via ``copilot_app_project``. Synchronous by design --------------------- @@ -45,7 +51,9 @@ import json import os +import re import socket +import stat import time from dataclasses import dataclass from pathlib import Path @@ -143,19 +151,64 @@ def _run_dir() -> Path: return Path.home() / _RUN_DIR +_TOKEN_QUERY_RE = re.compile(r"(\?|&)token=[^&\s\"'>]+") + + +def _scrub_token(text: str) -> str: + """Redact any ``?token=...`` / ``&token=...`` query material from *text*. + + Used before wrapping ``websockets`` library exceptions into our + ``WsError`` subtypes: those exception messages frequently echo back + the full handshake URL, which embeds the per-launch token. The + token is short-lived but still credential material, so we keep it + out of diagnostics, log lines, and user-visible warnings. + """ + return _TOKEN_QUERY_RE.sub(r"\1token=", text) + + +def _token_file_mode_ok(path: Path) -> bool: + """Return True iff the token file has no group/other permissions. + + The App writes the file as 0o600. If a later actor (user, backup + tool, sync agent) widens the mode, anything readable by group or + other can lift the token and impersonate APM against the App's WS + server for as long as the App stays open. We treat any + group/other bit as a refusal-to-read rather than warning-and- + continuing -- the SQLite fallback is always available, so the + cost of being strict is one extra restart, while the cost of being + permissive is a real credential leak. + + POSIX-only check. On Windows ``stat.S_IRWXG`` / ``stat.S_IRWXO`` + are reported as zero by ``os.stat`` so the check is effectively a + no-op there; ACL hardening on Windows is out of scope for this + module. + """ + try: + st = path.stat() + except OSError: + return False + mode = st.st_mode + return not (mode & (stat.S_IRWXG | stat.S_IRWXO)) + + def _read_creds() -> tuple[int, str] | None: """Return ``(port, token)`` from the App's run-files or ``None``. Both files must exist and be readable; either missing means the App - is not running (or never has been since boot). We do not validate - the token format here -- the server rejects invalid tokens at - handshake. + is not running (or never has been since boot). The token file's + mode is verified to match the App's documented 0o600 posture -- + if widened to group/other-readable we refuse rather than risk + sending credential material extracted from a non-private file. + We do not validate the token format itself; the server rejects + invalid tokens at handshake. """ run = _run_dir() port_path = run / _PORT_FILE token_path = run / _TOKEN_FILE if not port_path.is_file() or not token_path.is_file(): return None + if not _token_file_mode_ok(token_path): + return None try: port = int(port_path.read_text(encoding="ascii").strip()) token = token_path.read_text(encoding="ascii").strip() @@ -205,18 +258,6 @@ class ProjectCreated: main_repo_path: str -@dataclass(frozen=True) -class WorkflowCreated: - """Outcome of ``create_workflow`` / ``update_workflow``. - - The App generates a UUIDv4 for new rows. APM's caller does not - depend on the format -- the id is opaque and only used to address - the row in subsequent ``update_workflow`` / delete calls. - """ - - workflow_id: str - - # --------------------------------------------------------------------------- # Client # --------------------------------------------------------------------------- @@ -230,12 +271,16 @@ class WsClient: with WsClient() as client: project = client.create_project_from_path(repo_root) - for wf in workflows: - client.create_workflow(...) + + The client exposes only ``create_project_from_path``: workflow + rows are written via direct SQLite (``copilot_app_db``) regardless + of which path created the project. This keeps lockfile ids + namespaced and stable (see module docstring). All public methods raise a ``WsError`` subtype on any failure; the caller in ``prompt_integrator._integrate_prompts_for_copilot_app`` - catches ``WsError`` and falls through to the SQLite path. + catches ``WsError`` and falls through to the SQLite project + registration path. """ def __init__(self, *, recv_timeout_s: float = _WS_RECV_TIMEOUT_S) -> None: @@ -298,16 +343,22 @@ def _connect(self) -> None: max_size=2**24, ) except Exception as exc: - msg = str(exc) + # Scrub the handshake URL's ``?token=`` before it + # lands in our exception text -- the ``websockets`` library + # echoes the full URL back in several of its InvalidStatus + # / InvalidHandshake messages. + raw = str(exc) + msg = _scrub_token(raw) + scrubbed_lower = msg.lower() # ``websockets`` raises InvalidStatus / InvalidHandshake for # HTTP-level rejections. 401/403 -> auth; everything else -> # generic protocol error. We string-match defensively so a # library-version bump doesn't break the branch. - if "401" in msg or "403" in msg or "unauthor" in msg.lower(): - raise WsAuthError(f"WS auth rejected: {exc}") from exc - if "refused" in msg.lower() or "ConnectionRefused" in msg: - raise WsAppNotRunning(f"WS connection refused: {exc}") from exc - raise WsProtocolError(f"WS handshake failed: {exc}") from exc + if "401" in msg or "403" in msg or "unauthor" in scrubbed_lower: + raise WsAuthError(f"WS auth rejected: {msg}") from None + if "refused" in scrubbed_lower or "connectionrefused" in scrubbed_lower: + raise WsAppNotRunning(f"WS connection refused: {msg}") from None + raise WsProtocolError(f"WS handshake failed: {msg}") from None # -- low-level send/recv ------------------------------------------- @@ -423,106 +474,12 @@ def create_project_from_path(self, path: Path) -> ProjectCreated: main_repo_path=main_repo_path or str(path), ) - def create_workflow( - self, - *, - name: str, - prompt: str, - interval: str = "manual", - mode: str | None = None, - schedule_hour: int = 9, - schedule_day: int = 1, - project_id: str | None = None, - enabled: bool = False, - ) -> WorkflowCreated: - """Create a workflow row through the App. - - The App generates the workflow's id (UUIDv4). ``enabled`` - defaults to ``False`` to match the install contract: APM never - flips the schedule on; the user opts in from the App UI. - """ - payload: dict[str, Any] = { - "type": "create_workflow", - "name": name, - "prompt": prompt, - "interval": interval, - "schedule_hour": schedule_hour, - "schedule_day": schedule_day, - "enabled": enabled, - } - if mode is not None: - payload["mode"] = mode - if project_id is not None: - payload["project_id"] = project_id - self._send(payload) - reply = self._await_typed_reply(expected={"workflow_created"}) - wid = _extract_workflow_id(reply) - if not wid: - raise WsProtocolError(f"workflow_created reply missing id: {reply!r}") - return WorkflowCreated(workflow_id=wid) - - def update_workflow( - self, - *, - workflow_id: str, - name: str | None = None, - prompt: str | None = None, - interval: str | None = None, - mode: str | None = None, - schedule_hour: int | None = None, - schedule_day: int | None = None, - project_id: str | None = None, - enabled: bool | None = None, - ) -> WorkflowCreated: - """Update an existing workflow row in place. - - Only fields explicitly passed are sent on the wire so the - server's partial-update semantics are preserved (unsent fields - keep their existing value). - """ - payload: dict[str, Any] = { - "type": "update_workflow", - "id": workflow_id, - } - for key, value in ( - ("name", name), - ("prompt", prompt), - ("interval", interval), - ("mode", mode), - ("schedule_hour", schedule_hour), - ("schedule_day", schedule_day), - ("project_id", project_id), - ("enabled", enabled), - ): - if value is not None: - payload[key] = value - self._send(payload) - reply = self._await_typed_reply( - expected={"workflow_updated", "workflow_created"}, - ) - wid = _extract_workflow_id(reply) or workflow_id - return WorkflowCreated(workflow_id=wid) - # --------------------------------------------------------------------------- # Permissive parsers # --------------------------------------------------------------------------- -def _extract_workflow_id(reply: dict[str, Any]) -> str | None: - """Pull the workflow id out of any of the shapes the server emits.""" - for key in ("id", "workflow_id"): - v = reply.get(key) - if isinstance(v, str) and v: - return v - wf = reply.get("workflow") - if isinstance(wf, dict): - v = wf.get("id") - if isinstance(v, str) and v: - return v - return None - - def _extract_project_fields( reply: dict[str, Any], *, diff --git a/src/apm_cli/integration/prompt_integrator.py b/src/apm_cli/integration/prompt_integrator.py index 591155112b..92f9fb442c 100644 --- a/src/apm_cli/integration/prompt_integrator.py +++ b/src/apm_cli/integration/prompt_integrator.py @@ -154,35 +154,41 @@ def _integrate_prompts_for_copilot_app( ) -> IntegrationResult: """Deploy workflow-shape prompts as Copilot App workflow rows. - Hybrid dispatch (PR A): + Hybrid dispatch: 1. Detect the repo at ``project_root``. Derive a stable - ``ProjectRecipe`` (id, name, github owner/repo, default - branch) so the workflow rows can be scoped to a real - ``projects`` row instead of orphaned at the root. + ``RepoContext`` (name, github owner/repo, default branch) so + workflow rows scope to a real ``projects`` row instead of + being orphaned at the root. 2. If ``user_scope`` is set AND any workflow-shape prompts are present, emit a warn-and-proceed diagnostic: workflows run with CWD=~/.copilot in global mode, which is almost never what the user wants. We still deploy so global skills / commands keep working; the user can attach the row to a project from the App UI. - 3. If the App is running (``ws_available``), try the WS-IPC - path: ``create_project_from_path`` then ``create_workflow`` - per prompt. The App generates UUIDs; we do not control the - row id but we get the live ``WorkflowsChanged`` broadcast - and avoid the project-not-loaded white-screen failure mode. - 4. Otherwise (or on any WS error), fall back to the direct - SQLite path: register / look up the project via - ``resolve_or_register_project_sqlite``, stamp ``project_id`` - on every row, and suffix the display name with ``()``. - - Workflow-shape (per ``_is_workflow_shape``) prompts deploy here. - Plain-shape prompts (no execution-affecting frontmatter keys) - are a hard error at this target: the user explicitly opted into - ``copilot-app`` for this package, and a plain prompt cannot - possibly be a workflow. Surfacing the mismatch loudly beats - silently skipping the file and leaving the user wondering why - nothing landed in the App. + 3. Resolve the ``project_id`` ONCE: if the App is running + (``ws_available``), try ``WsClient.create_project_from_path`` + so the project row goes through the App's own validation + (owner/repo detection, default branch, account binding) and + is already known to the webview. On any ``WsError`` (or if + the App is closed) fall through to direct SQLite via + ``resolve_or_register_project_sqlite``. + 4. Write every workflow row via direct SQLite + (``copilot_app_db.deploy_workflow``), stamped with the + resolved ``project_id`` and a namespaced + ``owner/pkg/stem`` id so the lockfile stays stable across + runs and across the WS-vs-SQLite project-resolution branch. + 5. If the project was freshly created (either branch), emit + the one-time restart hint -- the webview's projectStore + does not currently refresh on a new ``projects`` row. + + Workflow-shape (per ``_is_workflow_shape``) prompts deploy + here. Plain-shape prompts (no execution-affecting frontmatter + keys) are a hard error at this target: the user explicitly + opted into ``copilot-app`` for this package, and a plain + prompt cannot possibly be a workflow. Surfacing the mismatch + loudly beats silently skipping the file and leaving the user + wondering why nothing landed in the App. The DB module enforces ``enabled = 0`` on insert; any frontmatter ``enabled`` field, if present, is ignored. This is a hard @@ -203,6 +209,9 @@ def _integrate_prompts_for_copilot_app( resolve_or_register_project_sqlite, ) from apm_cli.integration.copilot_app_ws import ( + WsAppNotRunning, + WsAuthError, + WsClient, WsError, ws_available, ) @@ -216,7 +225,7 @@ def _integrate_prompts_for_copilot_app( # ------------------------------------------------------------------ # Parse all candidate prompts up front so we can decide on the - # WS path / SQLite path / global-scope warning with one pass. + # global-scope warning with one pass. # ------------------------------------------------------------------ parsed: list[tuple[Path, object, object]] = [] files_skipped = 0 @@ -270,58 +279,58 @@ def _integrate_prompts_for_copilot_app( ) # ------------------------------------------------------------------ - # Project scoping. + # Resolve project_id ONCE -- WS (preferred) then SQLite fallback. # ------------------------------------------------------------------ repo_ctx = derive_repo_context(project_root) repo_suffix = f" ({repo_ctx.repo_name})" if repo_ctx is not None else "" - - # WS path -- preferred when the App is running. We try it ONLY - # when we have a real repo context (a project to attach the - # workflows to); otherwise the WS path adds no value over the - # SQLite fallback. - if repo_ctx is not None and ws_available(): - try: - return self._deploy_via_ws( - repo_ctx=repo_ctx, - parsed=parsed, - pkg_name=pkg_name, - owner=owner, - files_skipped=files_skipped, - diagnostics=diagnostics, - db_path=db_path, - ) - except WsError as exc: - # Live App but WS path broke -- log and fall through to - # SQLite. We never let a transient WS failure turn into - # a hard install error. - if diagnostics is not None: - diagnostics.warn( - message=( - f"Copilot App live IPC unavailable ({exc}); " - "falling back to direct database write." - ), - package=pkg_name, - ) - - # ------------------------------------------------------------------ - # SQLite fallback path. - # ------------------------------------------------------------------ project_id: str | None = None was_created = False + if repo_ctx is not None: - try: - resolved = resolve_or_register_project_sqlite(db_path, repo_ctx) - project_id = resolved.project_id - was_created = resolved.was_created - except CopilotAppDbError as exc: - if diagnostics is not None: - diagnostics.warn( - message=( - f"Could not register project for Copilot App: {exc}. " - "Workflows will be installed without a project binding." - ), - package=pkg_name, - ) + if ws_available(): + try: + with WsClient() as client: + project = client.create_project_from_path(repo_ctx.repo_root) + project_id = project.project_id + was_created = project.was_created + except WsAppNotRunning: + # Race: ws_available() saw the port files but the + # App closed between probe and handshake. Silent + # fallback -- closed App is the normal off-state. + pass + except WsAuthError: + # Stale ``ws.token`` -- most often because the App + # rotated its token at restart. We fall back to + # SQLite silently rather than nag on every install: + # the user-visible signal is already the restart + # hint emitted further down, and the SQLite path + # produces an identical project row. + pass + except WsError as exc: + if diagnostics is not None: + diagnostics.warn( + message=( + f"Could not reach the running Copilot App " + f"({exc}). Registering the project directly " + "in the App database instead." + ), + package=pkg_name, + ) + + if project_id is None: + try: + resolved = resolve_or_register_project_sqlite(db_path, repo_ctx) + project_id = resolved.project_id + was_created = resolved.was_created + except CopilotAppDbError as exc: + if diagnostics is not None: + diagnostics.warn( + message=( + f"Could not register project for Copilot App: {exc}. " + "Workflows will be installed without a project binding." + ), + package=pkg_name, + ) if was_created and diagnostics is not None: # See github/github-app#5483 -- the App webview does not @@ -337,6 +346,10 @@ def _integrate_prompts_for_copilot_app( package=pkg_name, ) + # ------------------------------------------------------------------ + # Workflow rows -- always SQLite, regardless of project source. + # Keeps lockfile ids namespaced and stable. + # ------------------------------------------------------------------ synthetic_root = db_path.parent / "workflows" files_integrated = 0 target_paths: list[Path] = [] @@ -380,90 +393,6 @@ def _integrate_prompts_for_copilot_app( files_adopted=0, ) - def _deploy_via_ws( - self, - *, - repo_ctx, - parsed: list, - pkg_name: str, - owner: str, - files_skipped: int, - diagnostics, - db_path: Path, - ) -> IntegrationResult: - """Deploy workflow rows through the live App's WS-IPC surface. - - The App generates its own UUIDs for both the project and each - workflow; we do NOT use ``namespaced_id`` here. Lockfile - bookkeeping still uses the same ``copilot-app-db://workflows/`` - scheme so uninstall + sync stays consistent regardless of which - path created the row -- the id is opaque to the rest of APM. - """ - from apm_cli.integration.copilot_app_db import ( - WorkflowRow, - deploy_workflow, - namespaced_id, - ) - from apm_cli.integration.copilot_app_ws import WsClient - - repo_suffix = f" ({repo_ctx.repo_name})" - synthetic_root = db_path.parent / "workflows" - files_integrated = 0 - target_paths: list[Path] = [] - - with WsClient() as client: - try: - project = client.create_project_from_path(repo_ctx.repo_root) - except Exception: - raise - - if project.was_created and diagnostics is not None: - diagnostics.info( - message=( - "Registered a new Copilot App project for this repo. " - "If the Workflows tab does not refresh, restart the App once " - "(see github/github-app#5483)." - ), - package=pkg_name, - ) - - # The App generates row UUIDs server-side, but we ALSO write - # a namespaced row via the SQLite path so the lockfile keeps - # a stable, predictable id. We do the SQLite write here - # (same db_path the App opens) -- the App's row and ours - # coexist; uninstall removes ours by id. This avoids the - # "WS path breaks namespacing" problem flagged in the plan. - for source_file, post, schedule in parsed: - prompt_stem = source_file.name.removesuffix(".prompt.md") - wf_id = namespaced_id(owner, pkg_name, prompt_stem) - base_name = post.metadata.get("name") or prompt_stem - display_name = f"{base_name}{repo_suffix}" - row = WorkflowRow( - id=wf_id, - name=str(display_name), - prompt=post.content, - interval=schedule.interval, - schedule_hour=schedule.schedule_hour, - schedule_day=schedule.schedule_day, - enabled=0, - model=schedule.model, - reasoning_effort=schedule.reasoning_effort, - mode=schedule.mode, - project_id=project.project_id, - ) - deploy_workflow(db_path, row) - files_integrated += 1 - target_paths.append(synthetic_root / wf_id) - - return IntegrationResult( - files_integrated=files_integrated, - files_updated=0, - files_skipped=files_skipped, - target_paths=target_paths, - links_resolved=0, - files_adopted=0, - ) - def _sync_copilot_app(self, managed_files: set[str]) -> dict[str, int]: """Remove Copilot App workflow rows referenced by *managed_files*. diff --git a/tests/integration/test_copilot_app_ws_fallback.py b/tests/integration/test_copilot_app_ws_fallback.py new file mode 100644 index 0000000000..12066c084b --- /dev/null +++ b/tests/integration/test_copilot_app_ws_fallback.py @@ -0,0 +1,290 @@ +"""Integration test for the hybrid WS-then-SQLite project-registration +dispatch in ``PromptIntegrator._integrate_prompts_for_copilot_app``. + +The PR that introduced the hybrid path claims a single deterministic +contract: when the App is running (``ws_available() is True``) we try +``WsClient.create_project_from_path`` first; on any ``WsError`` we +fall through to ``resolve_or_register_project_sqlite``; in BOTH +branches the workflow rows are then written via direct SQLite stamped +with the resolved ``project_id``. + +The unit suite covers each branch in isolation but not the mid-deploy +``WsError`` fallback that the PR's own dispatch diagram highlights. +Without this test, a future refactor could silently bypass the SQLite +path on WsError (e.g. by raising out of the integrator instead of +catching) and no existing assertion would notice. This test is the +regression trap for that specific drift. +""" + +from __future__ import annotations + +import sqlite3 +import subprocess +from pathlib import Path +from types import SimpleNamespace + +from apm_cli.integration import copilot_app_ws as ws_mod +from apm_cli.integration.prompt_integrator import PromptIntegrator +from apm_cli.integration.targets import KNOWN_TARGETS + +_SCHEMA: str = """ +CREATE TABLE IF NOT EXISTS "projects" ( + id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + container_kind TEXT NOT NULL, + main_repo_path TEXT UNIQUE, + default_branch TEXT, + github_owner TEXT, + github_repo TEXT, + github_account_id TEXT, + tab_order INTEGER, + issue_prompt TEXT, + pull_request_prompt TEXT, + auto_open_in_browser INTEGER NOT NULL DEFAULT 1, + auto_approve INTEGER NOT NULL DEFAULT 1 +); +CREATE TABLE IF NOT EXISTS "workflows" ( + id TEXT PRIMARY KEY NOT NULL, + name TEXT NOT NULL, + prompt TEXT NOT NULL, + interval TEXT NOT NULL CHECK (interval IN ('manual', 'hourly', 'daily', 'weekly')), + schedule_hour INTEGER NOT NULL DEFAULT 9, + schedule_day INTEGER NOT NULL DEFAULT 1, + enabled INTEGER NOT NULL DEFAULT 1, + project_id TEXT, + mode TEXT, + model TEXT, + reasoning_effort TEXT +); +""" + + +WORKFLOW_PROMPT = """--- +name: Daily Digest +interval: daily +schedule_hour: 9 +mode: interactive +--- +Summarise yesterday's commits. +""" + + +def _init_db(path: Path) -> None: + conn = sqlite3.connect(str(path)) + try: + conn.executescript(_SCHEMA) + conn.execute("PRAGMA user_version = 13") + conn.commit() + finally: + conn.close() + + +def _git_init(repo: Path) -> None: + repo.mkdir(parents=True, exist_ok=True) + for args in ( + ["git", "init", "-q", "-b", "main"], + ["git", "config", "user.email", "t@t"], + ["git", "config", "user.name", "t"], + ["git", "remote", "add", "origin", "https://github.com/acme/widgets.git"], + ): + subprocess.run(args, cwd=repo, check=True) + + +def _make_pkg(repo: Path) -> SimpleNamespace: + pkg = repo / "node_modules" / "@acme" / "demo" + prompts = pkg / ".apm" / "prompts" + prompts.mkdir(parents=True) + (prompts / "daily-digest.prompt.md").write_text(WORKFLOW_PROMPT) + return SimpleNamespace( + install_path=pkg, + package=SimpleNamespace( + name="demo", + source="github:acme/demo", + author=None, + ), + ) + + +class _Diagnostics: + def __init__(self) -> None: + self.warns: list[dict] = [] + self.infos: list[dict] = [] + + def warn(self, **kwargs) -> None: + self.warns.append(kwargs) + + def info(self, **kwargs) -> None: + self.infos.append(kwargs) + + +def test_ws_error_mid_deploy_falls_through_to_sqlite_with_project_scoping( + tmp_path, monkeypatch +) -> None: + """WS available + create_project_from_path raises WsError -> + + 1. The integrator does NOT propagate the WsError. + 2. SQLite ``resolve_or_register_project_sqlite`` registers the + project at ``repo_root`` and assigns a ``project_id``. + 3. Each workflow row is stamped with that ``project_id``. + 4. A user-visible warn explains the WS path was unreachable. + 5. The one-time restart hint fires because the project was new. + """ + repo = tmp_path / "repo" + _git_init(repo) + + db_path = tmp_path / "data.db" + _init_db(db_path) + monkeypatch.setenv("APM_COPILOT_APP_DB", str(db_path)) + + pkg = _make_pkg(repo) + + # Force ws_available() True regardless of the host's real run-dir. + monkeypatch.setattr(ws_mod, "ws_available", lambda: True) + + # Make the WS client's create_project_from_path raise a generic + # WsProtocolError mid-deploy -- the exact failure mode the PR's + # hybrid-dispatch diagram highlights ("WsError -> SQLite"). + def boom(self, path): + raise ws_mod.WsProtocolError("simulated upstream protocol drift") + + monkeypatch.setattr(ws_mod.WsClient, "create_project_from_path", boom) + # ``__enter__`` calls ``_connect`` which tries to read creds; bypass + # that whole machinery -- we just need the method-on-an-instance + # to raise WsProtocolError to drive the fallback branch. + monkeypatch.setattr(ws_mod.WsClient, "_connect", lambda self: None) + monkeypatch.setattr(ws_mod.WsClient, "_drain", lambda self, timeout_s: []) + + target = KNOWN_TARGETS["copilot-app"] + diags = _Diagnostics() + + result = PromptIntegrator().integrate_prompts_for_target( + target, + pkg, + project_root=repo, + diagnostics=diags, + ) + + # Workflow row landed despite the WS branch failing. + assert result.files_integrated == 1 + assert result.files_skipped == 0 + + # SQLite has a projects row scoped to the repo and a workflows row + # carrying that project_id. + conn = sqlite3.connect(str(db_path)) + try: + projects = conn.execute("SELECT id, name, main_repo_path FROM projects").fetchall() + assert len(projects) == 1 + project_id, _project_name, main_repo_path = projects[0] + assert project_id # non-empty UUID + assert main_repo_path == str(repo.resolve()) + + workflows = conn.execute("SELECT id, name, project_id FROM workflows").fetchall() + assert len(workflows) == 1 + wf_id, wf_name, wf_project_id = workflows[0] + assert wf_project_id == project_id, ( + "Workflow row must be scoped to the SQLite-registered project" + ) + # Namespaced id discipline preserved across the fallback branch. + assert wf_id.startswith("apm--") + # Display name suffixed with (repo_name) for sidebar disambiguation. + assert "(widgets)" in wf_name or "(repo)" in wf_name + finally: + conn.close() + + # User-visible warn explains the WS-side failure in plain wording + # (no internal jargon like "WS-IPC" / "handshake" / "broadcast"). + ws_warns = [w for w in diags.warns if "Copilot App" in w.get("message", "")] + assert ws_warns, "expected a user-facing warn about the WS failure" + msg = ws_warns[0]["message"] + assert "Could not reach the running Copilot App" in msg + for jargon in ("WS-IPC", "handshake failed", "live IPC unavailable"): + assert jargon not in msg, f"User-facing warn must not leak {jargon!r}; got {msg!r}" + + # The one-time restart hint fires because the SQLite branch + # registered a brand-new project row. + restart_infos = [ + i for i in diags.infos if "Restart the Copilot App once" in i.get("message", "") + ] + assert len(restart_infos) == 1, ( + "Expected exactly one restart-once hint after the project was newly created" + ) + + +def test_ws_app_not_running_falls_through_silently(tmp_path, monkeypatch) -> None: + """WsAppNotRunning is the App-closed signal -- silent fallback, no warn.""" + repo = tmp_path / "repo" + _git_init(repo) + + db_path = tmp_path / "data.db" + _init_db(db_path) + monkeypatch.setenv("APM_COPILOT_APP_DB", str(db_path)) + + pkg = _make_pkg(repo) + + monkeypatch.setattr(ws_mod, "ws_available", lambda: True) + + def app_closed(self, path): + raise ws_mod.WsAppNotRunning("port file went away mid-handshake") + + monkeypatch.setattr(ws_mod.WsClient, "create_project_from_path", app_closed) + monkeypatch.setattr(ws_mod.WsClient, "_connect", lambda self: None) + monkeypatch.setattr(ws_mod.WsClient, "_drain", lambda self, timeout_s: []) + + target = KNOWN_TARGETS["copilot-app"] + diags = _Diagnostics() + + result = PromptIntegrator().integrate_prompts_for_target( + target, + pkg, + project_root=repo, + diagnostics=diags, + ) + + assert result.files_integrated == 1 + + # WsAppNotRunning is silent -- closed-App is the normal off-state. + ws_warns = [ + w for w in diags.warns if "Could not reach the running Copilot App" in w.get("message", "") + ] + assert ws_warns == [], "WsAppNotRunning must NOT surface a user-visible warn" + + +def test_ws_auth_error_falls_through_silently(tmp_path, monkeypatch) -> None: + """WsAuthError (stale token) is silent fallback -- the restart hint + already covers the user-visible signal; nagging on every install + is a UX regression flagged by the panel.""" + repo = tmp_path / "repo" + _git_init(repo) + + db_path = tmp_path / "data.db" + _init_db(db_path) + monkeypatch.setenv("APM_COPILOT_APP_DB", str(db_path)) + + pkg = _make_pkg(repo) + + monkeypatch.setattr(ws_mod, "ws_available", lambda: True) + + def stale_token(self, path): + raise ws_mod.WsAuthError("WS auth rejected: token=") + + monkeypatch.setattr(ws_mod.WsClient, "create_project_from_path", stale_token) + monkeypatch.setattr(ws_mod.WsClient, "_connect", lambda self: None) + monkeypatch.setattr(ws_mod.WsClient, "_drain", lambda self, timeout_s: []) + + target = KNOWN_TARGETS["copilot-app"] + diags = _Diagnostics() + + PromptIntegrator().integrate_prompts_for_target( + target, + pkg, + project_root=repo, + diagnostics=diags, + ) + + ws_warns = [ + w for w in diags.warns if "Could not reach the running Copilot App" in w.get("message", "") + ] + assert ws_warns == [], ( + "WsAuthError (stale token) must NOT surface a user-visible warn; " + "the restart-once hint already covers the signal" + ) diff --git a/tests/unit/integration/test_copilot_app_ws.py b/tests/unit/integration/test_copilot_app_ws.py index 8de7ca8759..43449d7fb4 100644 --- a/tests/unit/integration/test_copilot_app_ws.py +++ b/tests/unit/integration/test_copilot_app_ws.py @@ -94,8 +94,16 @@ def run_dir(tmp_path: Path, monkeypatch) -> Path: def _write_creds(run_dir: Path, port: int, token: str) -> None: - (run_dir / "ws.port").write_text(str(port), encoding="ascii") - (run_dir / "ws.token").write_text(token, encoding="ascii") + import os + + port_path = run_dir / "ws.port" + token_path = run_dir / "ws.token" + port_path.write_text(str(port), encoding="ascii") + token_path.write_text(token, encoding="ascii") + # Match the App's 0o600 posture so ``_read_creds`` accepts the + # token file -- the production module refuses to read a token + # that is group/other-readable (see _token_file_mode_ok). + os.chmod(token_path, 0o600) # --------------------------------------------------------------------------- @@ -279,77 +287,26 @@ def handler(websocket): assert r.project_id == "p-1" -class TestCreateWorkflow: - def test_round_trip_returns_id_and_omits_none_fields(self, run_dir: Path) -> None: - received: dict = {} - - def handler(websocket): - received["msg"] = json.loads(websocket.recv()) - websocket.send(json.dumps({"type": "workflow_created", "id": "wf-1"})) - - with _Server(handler) as srv: - _write_creds(run_dir, srv.port, "tok") - with ws.WsClient() as client: - r = client.create_workflow( - name="hello", - prompt="say hi", - mode="plan", - project_id="proj-1", - ) - assert r.workflow_id == "wf-1" - msg = received["msg"] - assert msg["type"] == "create_workflow" - assert msg["name"] == "hello" - assert msg["mode"] == "plan" - assert msg["project_id"] == "proj-1" - assert msg["enabled"] is False # default - - def test_workflow_id_from_nested_workflow_object(self, run_dir: Path) -> None: - def handler(websocket): - websocket.recv() - websocket.send(json.dumps({"type": "workflow_created", "workflow": {"id": "wf-2"}})) - - with _Server(handler) as srv: - _write_creds(run_dir, srv.port, "tok") - with ws.WsClient() as client: - r = client.create_workflow(name="n", prompt="p") - assert r.workflow_id == "wf-2" - - -class TestUpdateWorkflow: - def test_only_set_fields_are_sent(self, run_dir: Path) -> None: - received: dict = {} - - def handler(websocket): - received["msg"] = json.loads(websocket.recv()) - websocket.send(json.dumps({"type": "workflow_updated", "id": "wf-3"})) - - with _Server(handler) as srv: - _write_creds(run_dir, srv.port, "tok") - with ws.WsClient() as client: - client.update_workflow(workflow_id="wf-3", prompt="new") - msg = received["msg"] - assert msg["type"] == "update_workflow" - assert msg["id"] == "wf-3" - assert msg["prompt"] == "new" - # Unset fields must NOT be on the wire (partial update). - for key in ("name", "interval", "mode", "schedule_hour", "enabled"): - assert key not in msg - - class TestDrainAndInterleavedPush: def test_response_found_after_push_messages(self, run_dir: Path) -> None: def handler(websocket): websocket.recv() websocket.send(json.dumps({"type": "workflows_changed"})) websocket.send(json.dumps({"type": "github_auth_success"})) - websocket.send(json.dumps({"type": "workflow_created", "id": "wf-late"})) + websocket.send( + json.dumps( + { + "type": "project_created", + "project": {"id": "p-late", "main_repo_path": "/r"}, + } + ) + ) with _Server(handler) as srv: _write_creds(run_dir, srv.port, "tok") with ws.WsClient() as client: - r = client.create_workflow(name="n", prompt="p") - assert r.workflow_id == "wf-late" + r = client.create_project_from_path(Path("/r")) + assert r.project_id == "p-late" class TestRecvTimeout: @@ -363,4 +320,83 @@ def handler(websocket): _write_creds(run_dir, srv.port, "tok") with ws.WsClient(recv_timeout_s=0.3) as client: with pytest.raises(ws.WsProtocolError, match=r"timed out"): - client.create_workflow(name="n", prompt="p") + client.create_project_from_path(Path("/r")) + + +# --------------------------------------------------------------------------- +# Security hardenings (token scrub + file mode) +# --------------------------------------------------------------------------- + + +class TestTokenScrub: + def test_scrub_removes_token_query_arg(self) -> None: + url = "ws://127.0.0.1:51234/?token=ABC123xyz= HTTP rejected" + scrubbed = ws._scrub_token(url) + assert "ABC123xyz" not in scrubbed + assert "token=" in scrubbed + + def test_scrub_handles_token_in_chained_query(self) -> None: + s = "GET /api?foo=1&token=SECRET_VALUE&bar=2 failed" + scrubbed = ws._scrub_token(s) + assert "SECRET_VALUE" not in scrubbed + assert "token=" in scrubbed + + def test_auth_error_message_does_not_leak_token(self, run_dir: Path, monkeypatch) -> None: + """End-to-end: a real 401 from the server must not embed the token.""" + + def handler(websocket): + # Never reached -- request gate below returns 401. + websocket.recv() + + secret_token = "TOPSECRETtoken12345" + with _Server(handler, expect_token="OTHER") as srv: + _write_creds(run_dir, srv.port, secret_token) + client = ws.WsClient() + with pytest.raises(ws.WsAuthError) as excinfo: + client._connect() + # The token MUST NOT appear anywhere in the exception text or + # in any chained __context__ / __cause__ chain reachable from + # the wrapped exception. We use ``from None`` for exactly this + # reason -- guard it with a test. + assert secret_token not in str(excinfo.value) + chain = excinfo.value.__cause__ or excinfo.value.__context__ + # ``from None`` suppresses __cause__; __context__ is permitted + # (implicit during except handling) but only matters if Python + # prints it. We accept either: no chain at all, OR a chain + # whose stringification also redacts the token. + if chain is not None: + # __context__ is the original websockets exception. Its own + # str() may still contain the URL; we cannot rewrite that + # at the library level, but ``raise ... from None`` ensures + # neither the default traceback printer nor APM's + # diagnostics formatter walks back to it. + pass # accepted -- documented trade-off + + +class TestTokenFileMode: + def test_world_readable_token_is_rejected(self, run_dir: Path, monkeypatch) -> None: + import os + + _write_creds(run_dir, 12345, "tok") + token_path = run_dir / "ws.token" + # Widen the token file to be world-readable. + os.chmod(token_path, 0o644) + # ``_read_creds`` MUST refuse rather than return creds. + assert ws._read_creds() is None + # And the public liveness probe likewise reports unavailable. + assert ws.ws_available() is False + + def test_group_readable_token_is_rejected(self, run_dir: Path) -> None: + import os + + _write_creds(run_dir, 12345, "tok") + os.chmod(run_dir / "ws.token", 0o640) + assert ws._read_creds() is None + + def test_owner_only_token_is_accepted(self, run_dir: Path) -> None: + import os + + _write_creds(run_dir, 12345, "tok") + os.chmod(run_dir / "ws.token", 0o600) + creds = ws._read_creds() + assert creds == (12345, "tok") diff --git a/uv.lock b/uv.lock index 6a9f5e1c42..fa84df0e62 100644 --- a/uv.lock +++ b/uv.lock @@ -246,7 +246,7 @@ requires-dist = [ { name = "toml", specifier = ">=0.10.2" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=1.2.0" }, { name = "watchdog", specifier = ">=3.0.0" }, - { name = "websockets", specifier = ">=12" }, + { name = "websockets", specifier = ">=12,<17" }, ] provides-extras = ["dev", "build"] From ec6b12fd581e3b7377343cce054bb82b975ec80a Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 21:47:46 +0200 Subject: [PATCH 09/10] refactor(copilot-app): extract workflow integrator + fold Copilot review nits The copilot-app target deploys *.prompt.md as Copilot App workflow rows (SQLite + optional WS-IPC) instead of files. That path shared NOTHING with the file-based prompt deploy except the source artefact, but it was squatting inside PromptIntegrator (~300 lines of unrelated logic plus its own module-level frontmatter helpers). Extract into a sibling integrator so the file matches how agent_integrator / command_integrator / hook_integrator / instruction_integrator are organised. Refactor: * New src/apm_cli/integration/copilot_app_workflow_integrator.py with CopilotAppWorkflowIntegrator(BaseIntegrator). Inherits BaseIntegrator for find_files_by_glob only -- the file-based collision / link-resolution machinery is irrelevant on the workflow surface (deploy_workflow is an UPSERT keyed on a namespaced id; sync deletes by id from the lockfile). * PromptIntegrator.integrate_prompts_for_target and .sync_for_target keep one trivially small branch per method that delegates to the workflow integrator -- grep copilot-app in prompt_integrator.py and one call site appears for each direction. * Module-level frontmatter helpers (_is_workflow_shape, Schedule, _parse_workflow_frontmatter, _parse_schedule, _derive_package_owner) move with the path that uses them. Re-exported from prompt_integrator for back-compat with tests / external callers. * copilot_app_db / copilot_app_project / copilot_app_ws stay put -- they are already at the right level. Only prompt_integrator was oversized. * Test fixtures unchanged; the integration test that patches copilot_app_ws.WsClient.create_project_from_path still works because the import path did not move. Folded Copilot reviewer nits (PR #1431): * B1: when derive_repo_context(project_root) returns None AND workflow prompts are present AND scope is not user, emit a parallel warn to the existing --global warn. project_id=NULL workflows have the same CWD=~/.copilot pivot risk; the user deserves the same heads-up plus the fix recipe (run inside a git repo or attach from the App UI). * B2: WsClient.create_project_from_path docstring rewritten to match the implementation -- was_created is inferred from the reply type (project_created -> True, project_updated -> False) via _extract_project_fields, not 'always True'. Restart hint only fires on the project_created branch. * B3: _find_repo_root docstring no longer claims symlinks-in-the-chain are blocked. The cheap fix: drop the false claim. The 'right' fix (walk + reject symlinked parents) would break macOS /tmp -> /private/tmp and other legitimate symlinked-ancestor setups, and the threat model (user's own CWD, not adversary input) does not justify the cost. The .git-marker is_symlink() check stays as defence-in-depth. Behavior change: one new warn diagnostic when copilot-app workflows install without a detected git repo. Three pre-existing unit tests in test_copilot_app_error_ux.py updated to filter the new warn out of their per-prompt deploy-error counts (the no-repo warn fires once for the whole install; deploy-error warns are per-prompt). Test gate: 54 targeted + 2766 broad -- all pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../integration/copilot_app_project.py | 20 +- .../copilot_app_workflow_integrator.py | 552 ++++++++++++++++++ src/apm_cli/integration/copilot_app_ws.py | 20 +- src/apm_cli/integration/prompt_integrator.py | 489 ++-------------- .../integration/test_copilot_app_error_ux.py | 19 +- 5 files changed, 654 insertions(+), 446 deletions(-) create mode 100644 src/apm_cli/integration/copilot_app_workflow_integrator.py diff --git a/src/apm_cli/integration/copilot_app_project.py b/src/apm_cli/integration/copilot_app_project.py index a1b98c10dc..d6bbcb7424 100644 --- a/src/apm_cli/integration/copilot_app_project.py +++ b/src/apm_cli/integration/copilot_app_project.py @@ -198,8 +198,24 @@ def _find_repo_root(start: Path) -> Path | None: Returns the first ancestor containing ``.git`` (file or dir -- git worktrees use a file pointer), or ``None`` when no enclosing repo - is found. Symlinks in the chain are not followed (defense against - being lured into an attacker-controlled root). + is found. + + .. note:: + ``start`` is resolved with :meth:`pathlib.Path.resolve` so the + returned root is canonical (used as the UNIQUE key on + ``projects.main_repo_path``). This DOES follow symlinks in the + parent chain. The only symlink-rejection check here is on the + ``.git`` marker itself (``not git_marker.is_symlink()``), which + blocks the narrow case where an attacker plants a symlinked + ``.git`` pointer inside a directory under their control. + Defending against symlinked parent directories would require + switching to :meth:`Path.absolute` + an explicit per-component + walk, but that breaks legitimate setups where temp dirs (macOS + ``/tmp`` -> ``/private/tmp``) or user-controlled bind mounts + have symlinked ancestors. Project-creation already runs in the + user's own trust domain (CWD is a user-typed path), so this is + an acceptable trade-off; ``derive_repo_context`` callers should + not treat the returned path as adversary-controlled. """ start = start.resolve() for candidate in (start, *start.parents): diff --git a/src/apm_cli/integration/copilot_app_workflow_integrator.py b/src/apm_cli/integration/copilot_app_workflow_integrator.py new file mode 100644 index 0000000000..29456c65bb --- /dev/null +++ b/src/apm_cli/integration/copilot_app_workflow_integrator.py @@ -0,0 +1,552 @@ +"""Copilot App workflow deployment integrator. + +The ``copilot-app`` target is the odd one out in the integrator +family: instead of writing files to disk (``.github/prompts/``, +``.claude/``, etc.) it inserts rows into the GitHub Copilot desktop +App's SQLite ``workflows`` table -- optionally via the App's own +WebSocket IPC surface when the App is running. The two surfaces +(file-based prompts vs. App-DB workflow rows) share NOTHING except +the source artefact (``*.prompt.md`` files in ``.apm/prompts/``). + +This module owns the SQLite + WS-IPC path end-to-end. ``PromptIntegrator`` +keeps a trivially small dispatch branch that constructs a +``CopilotAppWorkflowIntegrator`` and forwards the call -- one grep for +``copilot-app`` in ``prompt_integrator.py`` lands on that delegation. + +Design notes +------------ + +* Inherits from ``BaseIntegrator`` for ``find_files_by_glob`` only; + it does NOT use ``check_collision``, ``sync_remove_files``, or any + of the file-based collision / link-resolution machinery. The + workflow surface has its own collision model: ``deploy_workflow`` + is an UPSERT against a namespaced primary key, and sync deletes by + id from the lockfile. +* Imports are top-level (no lazy imports). Pulling + ``copilot_app_db`` / ``copilot_app_project`` / ``copilot_app_ws`` + here keeps ``prompt_integrator`` lightweight without paying any + cost in the workflow path. +* Frontmatter helpers (``_is_workflow_shape``, + ``_parse_workflow_frontmatter``, ``Schedule``, + ``_derive_package_owner``) live in this module too: they are + workflow-specific shape predicates. ``prompt_integrator`` and + ``command_integrator`` import ``_is_workflow_shape`` from here for + the dispatch-by-shape skip on the file-based side. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +import frontmatter + +from apm_cli.integration import copilot_app_db as _db_mod +from apm_cli.integration import copilot_app_ws as _ws_mod +from apm_cli.integration.base_integrator import BaseIntegrator, IntegrationResult +from apm_cli.integration.copilot_app_db import ( + COPILOT_APP_LOCKFILE_PREFIX, + CopilotAppDbError, + WorkflowRow, + from_lockfile_uri, + is_copilot_app_uri, + namespaced_id, +) +from apm_cli.integration.copilot_app_project import ( + derive_repo_context, + resolve_or_register_project_sqlite, +) +from apm_cli.integration.copilot_app_ws import ( + WsAppNotRunning, + WsAuthError, + WsClient, + WsError, +) + +if TYPE_CHECKING: + from apm_cli.integration.targets import TargetProfile + + +# --------------------------------------------------------------------------- +# Schedule frontmatter helpers (workflow-shape predicates) +# --------------------------------------------------------------------------- + +_VALID_SCHEDULE_INTERVALS: frozenset[str] = frozenset({"manual", "hourly", "daily", "weekly"}) +_VALID_SCHEDULE_MODES: frozenset[str] = frozenset({"interactive", "plan"}) +"""Mirror of ``copilot_app_db._VALID_MODES``. ``autopilot`` is +deliberately omitted -- see that module's docstring for the +secure-by-default rationale.""" + +# Top-level frontmatter keys that mark a ``.prompt.md`` as a "workflow" +# (i.e. a prompt with execution metadata, destined for the Copilot App +# DB rather than slash-command file targets). Touching ANY of these +# keys at the top level of the frontmatter flips the dispatch shape. +# +# This is the Option B "dispatch by shape" predicate -- one folder +# (``.apm/prompts/``), one extension (``.prompt.md``), one integrator. +# A file with these keys ships to ``copilot-app`` and is skipped by +# slash-command targets; a file without them ships to slash-command +# targets and hard-errors at ``copilot-app``. +_WORKFLOW_SHAPE_KEYS: frozenset[str] = frozenset({"interval", "schedule_hour", "schedule_day"}) + + +def _is_workflow_shape(frontmatter_meta: dict) -> bool: + """Return True iff *frontmatter_meta* declares Copilot App execution metadata. + + Used to decide which target(s) a ``.prompt.md`` file is destined + for. The check is intentionally a SHAPE check rather than a flag + -- authors do not opt in with a sentinel; the presence of an + execution-affecting key is the opt-in. + + Only ``interval``, ``schedule_hour``, ``schedule_day`` are + unambiguous workflow markers. ``mode``, ``model``, and + ``reasoning_effort`` are deliberately EXCLUDED because they overload + with plain slash-command prompts: VSCode / Copilot prompts use + ``mode: agent|ask|edit``, can pin a ``model``, and can hint + ``reasoning_effort``. Treating those keys as workflow markers + would mis-route ordinary slash commands to the App DB. Authors who + want a manual-only workflow opt in with the explicit + ``interval: manual``. + """ + if not isinstance(frontmatter_meta, dict): + return False + return any(k in frontmatter_meta for k in _WORKFLOW_SHAPE_KEYS) + + +@dataclass(frozen=True) +class Schedule: + """Validated representation of a prompt's workflow frontmatter. + + All fields are pre-validated against the same constraints the + Copilot App's ``workflows`` schema enforces, so deploy time never + surfaces a raw SQLite ``CHECK`` violation to the user. + + Sourced from top-level frontmatter keys (Option B: flat dispatch + shape), not from a nested ``schedule:`` block. + """ + + interval: str = "manual" + schedule_hour: int = 9 + schedule_day: int = 1 + mode: str | None = None + model: str | None = None + reasoning_effort: str | None = None + + +def _parse_workflow_frontmatter(meta: dict) -> Schedule: + """Validate top-level workflow frontmatter keys and return a ``Schedule``. + + Reads ``interval``, ``schedule_hour``, ``schedule_day``, ``mode``, + ``model``, ``reasoning_effort`` directly from the prompt's + frontmatter. ``interval`` defaults to ``"manual"`` when any other + execution-shape key is present but ``interval`` is omitted -- a + manual-only workflow is the conservative default given the Copilot + App's universal "run now" affordance. + + Raises ``ValueError`` (with a human-readable message) on any + out-of-range or wrong-type field. ``mode: autopilot`` is rejected + here with a targeted diagnostic before it can hit the DB layer's + generic CHECK violation -- third-party packages cannot ship + autopilot prompts; the user must opt in from the App UI. + """ + if not isinstance(meta, dict): + raise ValueError("frontmatter must be a mapping") + + interval = str(meta.get("interval", "manual")) + if interval not in _VALID_SCHEDULE_INTERVALS: + raise ValueError( + f"interval must be one of {sorted(_VALID_SCHEDULE_INTERVALS)}, got {interval!r}" + ) + + hour = meta.get("schedule_hour", 9) + if not isinstance(hour, int) or not (0 <= hour <= 23): + raise ValueError(f"schedule_hour must be int 0..23, got {hour!r}") + + day = meta.get("schedule_day", 1) + if not isinstance(day, int) or not (0 <= day <= 6): + raise ValueError(f"schedule_day must be int 0..6, got {day!r}") + + mode = meta.get("mode") + if mode is not None: + mode = str(mode) + if mode == "autopilot": + raise ValueError( + "mode 'autopilot' is not accepted via apm install -- " + "APM does not deploy workflows on autopilot. " + "Set autopilot manually in the Copilot App after enabling the row." + ) + if mode not in _VALID_SCHEDULE_MODES: + raise ValueError(f"mode must be one of {sorted(_VALID_SCHEDULE_MODES)}, got {mode!r}") + + model = meta.get("model") + if model is not None and not isinstance(model, str): + raise ValueError(f"model must be a string, got {model!r}") + + reasoning_effort = meta.get("reasoning_effort") + if reasoning_effort is not None and not isinstance(reasoning_effort, str): + raise ValueError(f"reasoning_effort must be a string, got {reasoning_effort!r}") + + return Schedule( + interval=interval, + schedule_hour=hour, + schedule_day=day, + mode=mode, + model=model, + reasoning_effort=reasoning_effort, + ) + + +# Back-compat alias retained for test imports; new code should use +# ``_parse_workflow_frontmatter`` directly. +_parse_schedule = _parse_workflow_frontmatter + + +def _derive_package_owner(package_info) -> str: + """Best-effort owner-segment extraction for namespacing workflow ids. + + Looks at the package's ``source`` (GitHub-style ``owner/repo`` or + URL) first, then ``author``, then falls back to ``"local"`` for + locally-sourced packages. The returned string is slugified by the + DB-side ``namespaced_id`` helper, so any input is safe. + """ + pkg = package_info.package + source = getattr(pkg, "source", None) + if isinstance(source, str) and source: + # github:foo/bar, https://github.com/foo/bar, foo/bar + s = source.split("://", 1)[-1] + s = s.split(":", 1)[-1] + parts = [p for p in s.split("/") if p and p != "github.com"] + if parts: + return parts[0] + author = getattr(pkg, "author", None) + if isinstance(author, str) and author.strip(): + return author.strip() + return "local" + + +# --------------------------------------------------------------------------- +# Integrator +# --------------------------------------------------------------------------- + + +class CopilotAppWorkflowIntegrator(BaseIntegrator): + """Deploy ``*.prompt.md`` workflow rows to the Copilot App DB. + + The integrator owns the full lifecycle of the ``copilot-app`` + target: prompt discovery, workflow-shape filtering, project + resolution (WS-IPC preferred, SQLite fallback), and SQLite + workflow-row UPSERT. It is constructed and called by + ``PromptIntegrator.integrate_prompts_for_target`` when + ``target.name == "copilot-app"``; nothing else routes here. + """ + + # ------------------------------------------------------------------ + # Prompt discovery (mirrors PromptIntegrator.find_prompt_files) + # ------------------------------------------------------------------ + + def find_prompt_files(self, package_path: Path) -> list[Path]: + """Find all ``.prompt.md`` files in *package_path*. + + Same surface as ``PromptIntegrator.find_prompt_files`` -- the + two integrators discover prompts identically; only the + deploy-side is split. Re-defined here (instead of inheriting + from ``PromptIntegrator``) to keep the workflow integrator + decoupled from the file-based prompt integrator's other + methods (``copy_prompt``, ``integrate_package_prompts``, ...). + """ + return self.find_files_by_glob(package_path, "*.prompt.md", subdirs=[".apm/prompts"]) + + # ------------------------------------------------------------------ + # Integrate + # ------------------------------------------------------------------ + + def integrate( + self, + target: TargetProfile, + package_info, + *, + project_root: Path, + user_scope: bool, + force: bool, + diagnostics, + ) -> IntegrationResult: + """Deploy workflow-shape prompts as Copilot App workflow rows. + + Hybrid dispatch: + + 1. Detect the repo at ``project_root``. Derive a stable + ``RepoContext`` (name, github owner/repo, default branch) so + workflow rows scope to a real ``projects`` row instead of + being orphaned at the root. + 2. If ``user_scope`` is set AND any workflow-shape prompts are + present, emit a warn-and-proceed diagnostic: workflows run + with CWD=~/.copilot in global mode, which is almost never + what the user wants. We still deploy so global skills / + commands keep working; the user can attach the row to a + project from the App UI. + 3. If we COULD NOT detect a git repository at ``project_root`` + AND any workflow-shape prompts are present, emit a parallel + warn-and-proceed diagnostic: workflows install with + ``project_id=NULL`` which has the same CWD-pivot + characteristic as ``--global``. The user can attach the row + to a project from the App UI. + 4. Resolve the ``project_id`` ONCE: if the App is running + (``ws_available``), try ``WsClient.create_project_from_path`` + so the project row goes through the App's own validation + (owner/repo detection, default branch, account binding) and + is already known to the webview. On any ``WsError`` (or if + the App is closed) fall through to direct SQLite via + ``resolve_or_register_project_sqlite``. + 5. Write every workflow row via direct SQLite + (``copilot_app_db.deploy_workflow``), stamped with the + resolved ``project_id`` and a namespaced + ``owner/pkg/stem`` id so the lockfile stays stable across + runs and across the WS-vs-SQLite project-resolution branch. + 6. If the project was freshly created (either branch), emit + the one-time restart hint -- the webview's projectStore + does not currently refresh on a new ``projects`` row. + + Workflow-shape (per ``_is_workflow_shape``) prompts deploy + here. Plain-shape prompts (no execution-affecting frontmatter + keys) are a hard error at this target: the user explicitly + opted into ``copilot-app`` for this package, and a plain + prompt cannot possibly be a workflow. Surfacing the mismatch + loudly beats silently skipping the file and leaving the user + wondering why nothing landed in the App. + + The DB module enforces ``enabled = 0`` on insert; any frontmatter + ``enabled`` field, if present, is ignored. This is a hard + contract: third-party packages cannot auto-run anything on the + user's machine. + """ + db_path = _db_mod.resolve_copilot_app_db_path() + if db_path is None: + return IntegrationResult(0, 0, 0, []) + + owner = _derive_package_owner(package_info) + pkg_name = package_info.package.name + + # -------------------------------------------------------------- + # Parse all candidate prompts up front so we can decide on the + # global-scope / no-repo warnings with one pass. + # -------------------------------------------------------------- + parsed: list[tuple[Path, object, Schedule]] = [] + files_skipped = 0 + for source_file in self.find_prompt_files(package_info.install_path): + if source_file.is_symlink(): + if diagnostics is not None: + diagnostics.warn( + message=f"Refusing to read symlink prompt: {source_file}", + package=pkg_name, + ) + files_skipped += 1 + continue + post = frontmatter.load(str(source_file)) + if not _is_workflow_shape(post.metadata): + if diagnostics is not None: + diagnostics.warn( + message=( + f"Copilot App: {source_file.name} has no workflow frontmatter " + "(missing one of: interval, schedule_hour, schedule_day). " + "Add `interval: manual` to deploy it as a manual-trigger " + "workflow, or unset --target copilot-app." + ), + package=pkg_name, + ) + files_skipped += 1 + continue + try: + schedule = _parse_workflow_frontmatter(post.metadata) + except ValueError as exc: + if diagnostics is not None: + diagnostics.warn( + message=f"Invalid workflow frontmatter in {source_file.name}: {exc}", + package=pkg_name, + ) + files_skipped += 1 + continue + parsed.append((source_file, post, schedule)) + + # -------------------------------------------------------------- + # --global + workflow-shape: warn but proceed. + # -------------------------------------------------------------- + if user_scope and parsed and diagnostics is not None: + diagnostics.warn( + message=( + "Copilot App workflows installed with --global run with CWD=~/.copilot, " + "not a project. Attach the workflow to a project from the App's Workflows " + "tab to fix this, or re-run `apm install` from a repo without --global. " + "See https://aka.ms/apm/copilot-app-global for details." + ), + package=pkg_name, + ) + + # -------------------------------------------------------------- + # Resolve project_id ONCE -- WS (preferred) then SQLite fallback. + # -------------------------------------------------------------- + repo_ctx = derive_repo_context(project_root) + repo_suffix = f" ({repo_ctx.repo_name})" if repo_ctx is not None else "" + project_id: str | None = None + was_created = False + + # -------------------------------------------------------------- + # No git repo + workflow-shape: same CWD-pivot risk as --global. + # workflow rows land with project_id=NULL, which means "Run now" + # CWDs into ~/.copilot. Warn parallel to the --global branch. + # -------------------------------------------------------------- + if repo_ctx is None and parsed and not user_scope and diagnostics is not None: + diagnostics.warn( + message=( + "Copilot App workflows installed without a project binding: " + "could not detect a git repository for this install. " + "Workflows will run with CWD=~/.copilot, not a project. " + "Re-run `apm install` from inside a git repo, or attach the " + "workflow to a project from the App's Workflows tab." + ), + package=pkg_name, + ) + + if repo_ctx is not None: + if _ws_mod.ws_available(): + try: + with WsClient() as client: + project = client.create_project_from_path(repo_ctx.repo_root) + project_id = project.project_id + was_created = project.was_created + except WsAppNotRunning: + # Race: ws_available() saw the port files but the + # App closed between probe and handshake. Silent + # fallback -- closed App is the normal off-state. + pass + except WsAuthError: + # Stale ``ws.token`` -- most often because the App + # rotated its token at restart. We fall back to + # SQLite silently rather than nag on every install: + # the user-visible signal is already the restart + # hint emitted further down, and the SQLite path + # produces an identical project row. + pass + except WsError as exc: + if diagnostics is not None: + diagnostics.warn( + message=( + f"Could not reach the running Copilot App " + f"({exc}). Registering the project directly " + "in the App database instead." + ), + package=pkg_name, + ) + + if project_id is None: + try: + resolved = resolve_or_register_project_sqlite(db_path, repo_ctx) + project_id = resolved.project_id + was_created = resolved.was_created + except CopilotAppDbError as exc: + if diagnostics is not None: + diagnostics.warn( + message=( + f"Could not register project for Copilot App: {exc}. " + "Workflows will be installed without a project binding." + ), + package=pkg_name, + ) + + if was_created and diagnostics is not None: + # See github/github-app#5483 -- the App webview does not + # currently refresh on externally-inserted ``projects`` + # rows. A one-time restart wires the new project into the + # UI; subsequent installs into the same repo are silent. + diagnostics.info( + message=( + "Registered a new Copilot App project for this repo. " + "Restart the Copilot App once so the new project appears in the UI " + "(see github/github-app#5483)." + ), + package=pkg_name, + ) + + # -------------------------------------------------------------- + # Workflow rows -- always SQLite, regardless of project source. + # Keeps lockfile ids namespaced and stable. + # -------------------------------------------------------------- + synthetic_root = db_path.parent / "workflows" + files_integrated = 0 + target_paths: list[Path] = [] + for source_file, post, schedule in parsed: + prompt_stem = source_file.name.removesuffix(".prompt.md") + wf_id = namespaced_id(owner, pkg_name, prompt_stem) + base_name = post.metadata.get("name") or prompt_stem + display_name = f"{base_name}{repo_suffix}" + row = WorkflowRow( + id=wf_id, + name=str(display_name), + prompt=post.content, + interval=schedule.interval, + schedule_hour=schedule.schedule_hour, + schedule_day=schedule.schedule_day, + enabled=0, # ALWAYS disabled on install -- contract. + model=schedule.model, + reasoning_effort=schedule.reasoning_effort, + mode=schedule.mode, + project_id=project_id, + ) + try: + _db_mod.deploy_workflow(db_path, row) + except CopilotAppDbError as exc: + if diagnostics is not None: + diagnostics.warn( + message=f"Could not deploy {prompt_stem!r} to Copilot App: {exc}", + package=pkg_name, + ) + files_skipped += 1 + continue + files_integrated += 1 + target_paths.append(synthetic_root / wf_id) + + return IntegrationResult( + files_integrated=files_integrated, + files_updated=0, + files_skipped=files_skipped, + target_paths=target_paths, + links_resolved=0, + files_adopted=0, + ) + + # ------------------------------------------------------------------ + # Sync (uninstall) + # ------------------------------------------------------------------ + + def sync(self, managed_files: set[str]) -> dict[str, int]: + """Remove Copilot App workflow rows referenced by *managed_files*. + + Filters the input set to ``copilot-app-db://workflows/`` URIs, + decodes the workflow ids, and deletes them in a single + transaction. Non-APM-namespaced ids are rejected by + ``copilot_app_db.delete_workflows`` for defence in depth. + """ + ids: list[str] = [] + for entry in managed_files: + if not is_copilot_app_uri(entry): + continue + if not entry.startswith(COPILOT_APP_LOCKFILE_PREFIX): + continue + try: + ids.append(from_lockfile_uri(entry)) + except ValueError: + # Malformed entry -- skip rather than fail uninstall. + continue + if not ids: + return {"files_removed": 0, "errors": 0} + + db_path = _db_mod.resolve_copilot_app_db_path() + if db_path is None: + # DB gone -- nothing to remove; treat as success (idempotent). + return {"files_removed": 0, "errors": 0} + + try: + removed = _db_mod.delete_workflows(db_path, ids) + except CopilotAppDbError: + return {"files_removed": 0, "errors": 1} + return {"files_removed": removed, "errors": 0} diff --git a/src/apm_cli/integration/copilot_app_ws.py b/src/apm_cli/integration/copilot_app_ws.py index eb0c27c344..21cd3cb268 100644 --- a/src/apm_cli/integration/copilot_app_ws.py +++ b/src/apm_cli/integration/copilot_app_ws.py @@ -446,13 +446,19 @@ def create_project_from_path(self, path: Path) -> ProjectCreated: owner/repo detection, default-branch resolution, account binding. We get back the resolved ``project_id``. - ``was_created`` is best-effort: the server's - ``project_created`` reply carries a ``project`` payload but - not (currently) a "was new" flag, so we treat any successful - reply as "created or already existed -- caller should ALWAYS - emit the restart hint until upstream issue github/github-app#5483 - lands the live broadcast". The hint is suppressed once the - webview learns about the row (i.e. after the user restarts). + ``was_created`` is inferred from the server's reply type: + ``project_created`` -> ``was_created=True`` (new ``projects`` row), + ``project_updated`` -> ``was_created=False`` (HIT on existing + ``main_repo_path``). The restart hint downstream only fires on + ``was_created=True``; on ``project_updated`` the webview already + knows the row and no restart is needed. The "was new" flag rides + on the message ``type`` rather than a dedicated field -- see + ``_extract_project_fields`` for the parser. + + Upstream issue github/github-app#5483 tracks adding a live + broadcast so externally-inserted rows surface in the webview + without a restart; until that lands, the hint is the user-visible + signal that a manual restart wires the new project into the UI. """ self._send( { diff --git a/src/apm_cli/integration/prompt_integrator.py b/src/apm_cli/integration/prompt_integrator.py index 92f9fb442c..0073b53e7c 100644 --- a/src/apm_cli/integration/prompt_integrator.py +++ b/src/apm_cli/integration/prompt_integrator.py @@ -86,12 +86,19 @@ def integrate_prompts_for_target( # lifecycle for this target -- it does not share the file-based # collision / link-resolution machinery. if target.name == "copilot-app": + # Delegate to the workflow integrator -- file-based and + # SQLite-row deploy share NOTHING except the source + # artefact. See copilot_app_workflow_integrator.py. + from apm_cli.integration.copilot_app_workflow_integrator import ( + CopilotAppWorkflowIntegrator, + ) + # Detect --global / user-scope by name; we accept either the # InstallScope enum or a string. Avoids a hard import cycle. user_scope = False if scope is not None: user_scope = getattr(scope, "name", str(scope)).upper() == "USER" - return self._integrate_prompts_for_copilot_app( + return CopilotAppWorkflowIntegrator().integrate( target, package_info, project_root=project_root, @@ -124,7 +131,11 @@ def sync_for_target( return {"files_removed": 0, "errors": 0} if target.name == "copilot-app": - return self._sync_copilot_app(managed_files or set()) + from apm_cli.integration.copilot_app_workflow_integrator import ( + CopilotAppWorkflowIntegrator, + ) + + return CopilotAppWorkflowIntegrator().sync(managed_files or set()) effective_root = mapping.deploy_root or target.root_dir prefix = f"{effective_root}/{mapping.subdir}/" @@ -139,7 +150,10 @@ def sync_for_target( ) # ------------------------------------------------------------------ - # copilot-app SQLite path + # copilot-app SQLite path -- MOVED to copilot_app_workflow_integrator.py. + # The methods below are kept as thin shims for back-compat with any + # external caller / test that imported them directly. They will be + # removed in a future major. # ------------------------------------------------------------------ def _integrate_prompts_for_copilot_app( @@ -152,288 +166,34 @@ def _integrate_prompts_for_copilot_app( force: bool, diagnostics, ) -> IntegrationResult: - """Deploy workflow-shape prompts as Copilot App workflow rows. - - Hybrid dispatch: - - 1. Detect the repo at ``project_root``. Derive a stable - ``RepoContext`` (name, github owner/repo, default branch) so - workflow rows scope to a real ``projects`` row instead of - being orphaned at the root. - 2. If ``user_scope`` is set AND any workflow-shape prompts are - present, emit a warn-and-proceed diagnostic: workflows run - with CWD=~/.copilot in global mode, which is almost never - what the user wants. We still deploy so global skills / - commands keep working; the user can attach the row to a - project from the App UI. - 3. Resolve the ``project_id`` ONCE: if the App is running - (``ws_available``), try ``WsClient.create_project_from_path`` - so the project row goes through the App's own validation - (owner/repo detection, default branch, account binding) and - is already known to the webview. On any ``WsError`` (or if - the App is closed) fall through to direct SQLite via - ``resolve_or_register_project_sqlite``. - 4. Write every workflow row via direct SQLite - (``copilot_app_db.deploy_workflow``), stamped with the - resolved ``project_id`` and a namespaced - ``owner/pkg/stem`` id so the lockfile stays stable across - runs and across the WS-vs-SQLite project-resolution branch. - 5. If the project was freshly created (either branch), emit - the one-time restart hint -- the webview's projectStore - does not currently refresh on a new ``projects`` row. - - Workflow-shape (per ``_is_workflow_shape``) prompts deploy - here. Plain-shape prompts (no execution-affecting frontmatter - keys) are a hard error at this target: the user explicitly - opted into ``copilot-app`` for this package, and a plain - prompt cannot possibly be a workflow. Surfacing the mismatch - loudly beats silently skipping the file and leaving the user - wondering why nothing landed in the App. - - The DB module enforces ``enabled = 0`` on insert; any frontmatter - ``enabled`` field, if present, is ignored. This is a hard - contract: third-party packages cannot auto-run anything on the - user's machine. + """Back-compat shim -- forwards to CopilotAppWorkflowIntegrator.integrate. + + The real implementation moved to + apm_cli.integration.copilot_app_workflow_integrator. Kept here so + external callers / tests that still reference the method-on-PromptIntegrator + attribute continue to work. New code should construct + CopilotAppWorkflowIntegrator directly. """ - import frontmatter - - from apm_cli.integration.copilot_app_db import ( - CopilotAppDbError, - WorkflowRow, - deploy_workflow, - namespaced_id, - resolve_copilot_app_db_path, + from apm_cli.integration.copilot_app_workflow_integrator import ( + CopilotAppWorkflowIntegrator, ) - from apm_cli.integration.copilot_app_project import ( - derive_repo_context, - resolve_or_register_project_sqlite, - ) - from apm_cli.integration.copilot_app_ws import ( - WsAppNotRunning, - WsAuthError, - WsClient, - WsError, - ws_available, - ) - - db_path = resolve_copilot_app_db_path() - if db_path is None: - return IntegrationResult(0, 0, 0, []) - - owner = _derive_package_owner(package_info) - pkg_name = package_info.package.name - - # ------------------------------------------------------------------ - # Parse all candidate prompts up front so we can decide on the - # global-scope warning with one pass. - # ------------------------------------------------------------------ - parsed: list[tuple[Path, object, object]] = [] - files_skipped = 0 - for source_file in self.find_prompt_files(package_info.install_path): - if source_file.is_symlink(): - if diagnostics is not None: - diagnostics.warn( - message=f"Refusing to read symlink prompt: {source_file}", - package=pkg_name, - ) - files_skipped += 1 - continue - post = frontmatter.load(str(source_file)) - if not _is_workflow_shape(post.metadata): - if diagnostics is not None: - diagnostics.warn( - message=( - f"Copilot App: {source_file.name} has no workflow frontmatter " - "(missing one of: interval, schedule_hour, schedule_day). " - "Add `interval: manual` to deploy it as a manual-trigger " - "workflow, or unset --target copilot-app." - ), - package=pkg_name, - ) - files_skipped += 1 - continue - try: - schedule = _parse_workflow_frontmatter(post.metadata) - except ValueError as exc: - if diagnostics is not None: - diagnostics.warn( - message=f"Invalid workflow frontmatter in {source_file.name}: {exc}", - package=pkg_name, - ) - files_skipped += 1 - continue - parsed.append((source_file, post, schedule)) - - # ------------------------------------------------------------------ - # --global + workflow-shape: warn but proceed. - # ------------------------------------------------------------------ - if user_scope and parsed and diagnostics is not None: - diagnostics.warn( - message=( - "Copilot App workflows installed with --global run with CWD=~/.copilot, " - "not a project. Attach the workflow to a project from the App's Workflows " - "tab to fix this, or re-run `apm install` from a repo without --global. " - "See https://aka.ms/apm/copilot-app-global for details." - ), - package=pkg_name, - ) - - # ------------------------------------------------------------------ - # Resolve project_id ONCE -- WS (preferred) then SQLite fallback. - # ------------------------------------------------------------------ - repo_ctx = derive_repo_context(project_root) - repo_suffix = f" ({repo_ctx.repo_name})" if repo_ctx is not None else "" - project_id: str | None = None - was_created = False - - if repo_ctx is not None: - if ws_available(): - try: - with WsClient() as client: - project = client.create_project_from_path(repo_ctx.repo_root) - project_id = project.project_id - was_created = project.was_created - except WsAppNotRunning: - # Race: ws_available() saw the port files but the - # App closed between probe and handshake. Silent - # fallback -- closed App is the normal off-state. - pass - except WsAuthError: - # Stale ``ws.token`` -- most often because the App - # rotated its token at restart. We fall back to - # SQLite silently rather than nag on every install: - # the user-visible signal is already the restart - # hint emitted further down, and the SQLite path - # produces an identical project row. - pass - except WsError as exc: - if diagnostics is not None: - diagnostics.warn( - message=( - f"Could not reach the running Copilot App " - f"({exc}). Registering the project directly " - "in the App database instead." - ), - package=pkg_name, - ) - - if project_id is None: - try: - resolved = resolve_or_register_project_sqlite(db_path, repo_ctx) - project_id = resolved.project_id - was_created = resolved.was_created - except CopilotAppDbError as exc: - if diagnostics is not None: - diagnostics.warn( - message=( - f"Could not register project for Copilot App: {exc}. " - "Workflows will be installed without a project binding." - ), - package=pkg_name, - ) - - if was_created and diagnostics is not None: - # See github/github-app#5483 -- the App webview does not - # currently refresh on externally-inserted ``projects`` - # rows. A one-time restart wires the new project into the - # UI; subsequent installs into the same repo are silent. - diagnostics.info( - message=( - "Registered a new Copilot App project for this repo. " - "Restart the Copilot App once so the new project appears in the UI " - "(see github/github-app#5483)." - ), - package=pkg_name, - ) - - # ------------------------------------------------------------------ - # Workflow rows -- always SQLite, regardless of project source. - # Keeps lockfile ids namespaced and stable. - # ------------------------------------------------------------------ - synthetic_root = db_path.parent / "workflows" - files_integrated = 0 - target_paths: list[Path] = [] - for source_file, post, schedule in parsed: - prompt_stem = source_file.name.removesuffix(".prompt.md") - wf_id = namespaced_id(owner, pkg_name, prompt_stem) - base_name = post.metadata.get("name") or prompt_stem - display_name = f"{base_name}{repo_suffix}" - row = WorkflowRow( - id=wf_id, - name=str(display_name), - prompt=post.content, - interval=schedule.interval, - schedule_hour=schedule.schedule_hour, - schedule_day=schedule.schedule_day, - enabled=0, # ALWAYS disabled on install -- contract. - model=schedule.model, - reasoning_effort=schedule.reasoning_effort, - mode=schedule.mode, - project_id=project_id, - ) - try: - deploy_workflow(db_path, row) - except CopilotAppDbError as exc: - if diagnostics is not None: - diagnostics.warn( - message=f"Could not deploy {prompt_stem!r} to Copilot App: {exc}", - package=pkg_name, - ) - files_skipped += 1 - continue - files_integrated += 1 - target_paths.append(synthetic_root / wf_id) - return IntegrationResult( - files_integrated=files_integrated, - files_updated=0, - files_skipped=files_skipped, - target_paths=target_paths, - links_resolved=0, - files_adopted=0, + return CopilotAppWorkflowIntegrator().integrate( + target, + package_info, + project_root=project_root, + user_scope=user_scope, + force=force, + diagnostics=diagnostics, ) def _sync_copilot_app(self, managed_files: set[str]) -> dict[str, int]: - """Remove Copilot App workflow rows referenced by *managed_files*. - - Filters the input set to ``copilot-app-db://workflows/`` URIs, - decodes the workflow ids, and deletes them in a single - transaction. Non-APM-namespaced ids are rejected by - ``copilot_app_db.delete_workflows`` for defence in depth. - """ - from apm_cli.integration.copilot_app_db import ( - COPILOT_APP_LOCKFILE_PREFIX, - CopilotAppDbError, - delete_workflows, - from_lockfile_uri, - is_copilot_app_uri, - resolve_copilot_app_db_path, + """Back-compat shim -- forwards to CopilotAppWorkflowIntegrator.sync.""" + from apm_cli.integration.copilot_app_workflow_integrator import ( + CopilotAppWorkflowIntegrator, ) - ids: list[str] = [] - for entry in managed_files: - if not is_copilot_app_uri(entry): - continue - if not entry.startswith(COPILOT_APP_LOCKFILE_PREFIX): - continue - try: - ids.append(from_lockfile_uri(entry)) - except ValueError: - # Malformed entry -- skip rather than fail uninstall. - continue - if not ids: - return {"files_removed": 0, "errors": 0} - - db_path = resolve_copilot_app_db_path() - if db_path is None: - # DB gone -- nothing to remove; treat as success (idempotent). - return {"files_removed": 0, "errors": 0} - - try: - removed = delete_workflows(db_path, ids) - except CopilotAppDbError: - return {"files_removed": 0, "errors": 1} - return {"files_removed": removed, "errors": 0} + return CopilotAppWorkflowIntegrator().sync(managed_files) # ------------------------------------------------------------------ # Legacy per-target API (DEPRECATED) @@ -581,159 +341,26 @@ def sync_integration( # --------------------------------------------------------------------------- -# Schedule frontmatter helpers (copilot-app target) -# --------------------------------------------------------------------------- - -from dataclasses import dataclass # noqa: E402 - -_VALID_SCHEDULE_INTERVALS: frozenset[str] = frozenset({"manual", "hourly", "daily", "weekly"}) -_VALID_SCHEDULE_MODES: frozenset[str] = frozenset({"interactive", "plan"}) -"""Mirror of ``copilot_app_db._VALID_MODES``. ``autopilot`` is -deliberately omitted -- see that module's docstring for the -secure-by-default rationale.""" - -# Top-level frontmatter keys that mark a ``.prompt.md`` as a "workflow" -# (i.e. a prompt with execution metadata, destined for the Copilot App -# DB rather than slash-command file targets). Touching ANY of these -# keys at the top level of the frontmatter flips the dispatch shape. +# Schedule frontmatter helpers -- MOVED to copilot_app_workflow_integrator. # -# This is the Option B "dispatch by shape" predicate -- one folder -# (``.apm/prompts/``), one extension (``.prompt.md``), one integrator. -# A file with these keys ships to ``copilot-app`` and is skipped by -# slash-command targets; a file without them ships to slash-command -# targets and hard-errors at ``copilot-app``. -_WORKFLOW_SHAPE_KEYS: frozenset[str] = frozenset({"interval", "schedule_hour", "schedule_day"}) - - -def _is_workflow_shape(frontmatter_meta: dict) -> bool: - """Return True iff *frontmatter_meta* declares Copilot App execution metadata. - - Used to decide which target(s) a ``.prompt.md`` file is destined - for. The check is intentionally a SHAPE check rather than a flag - -- authors do not opt in with a sentinel; the presence of an - execution-affecting key is the opt-in. - - Only ``interval``, ``schedule_hour``, ``schedule_day`` are - unambiguous workflow markers. ``mode``, ``model``, and - ``reasoning_effort`` are deliberately EXCLUDED because they overload - with plain slash-command prompts: VSCode / Copilot prompts use - ``mode: agent|ask|edit``, can pin a ``model``, and can hint - ``reasoning_effort``. Treating those keys as workflow markers - would mis-route ordinary slash commands to the App DB. Authors who - want a manual-only workflow opt in with the explicit - ``interval: manual``. - """ - if not isinstance(frontmatter_meta, dict): - return False - return any(k in frontmatter_meta for k in _WORKFLOW_SHAPE_KEYS) - - -@dataclass(frozen=True) -class Schedule: - """Validated representation of a prompt's workflow frontmatter. - - All fields are pre-validated against the same constraints the - Copilot App's ``workflows`` schema enforces, so deploy time never - surfaces a raw SQLite ``CHECK`` violation to the user. - - Sourced from top-level frontmatter keys (Option B: flat dispatch - shape), not from a nested ``schedule:`` block. - """ - - interval: str = "manual" - schedule_hour: int = 9 - schedule_day: int = 1 - mode: str | None = None - model: str | None = None - reasoning_effort: str | None = None - - -def _parse_workflow_frontmatter(meta: dict) -> Schedule: - """Validate top-level workflow frontmatter keys and return a ``Schedule``. - - Reads ``interval``, ``schedule_hour``, ``schedule_day``, ``mode``, - ``model``, ``reasoning_effort`` directly from the prompt's - frontmatter. ``interval`` defaults to ``"manual"`` when any other - execution-shape key is present but ``interval`` is omitted -- a - manual-only workflow is the conservative default given the Copilot - App's universal "run now" affordance. - - Raises ``ValueError`` (with a human-readable message) on any - out-of-range or wrong-type field. ``mode: autopilot`` is rejected - here with a targeted diagnostic before it can hit the DB layer's - generic CHECK violation -- third-party packages cannot ship - autopilot prompts; the user must opt in from the App UI. - """ - if not isinstance(meta, dict): - raise ValueError("frontmatter must be a mapping") - - interval = str(meta.get("interval", "manual")) - if interval not in _VALID_SCHEDULE_INTERVALS: - raise ValueError( - f"interval must be one of {sorted(_VALID_SCHEDULE_INTERVALS)}, got {interval!r}" - ) +# Re-exported here for back-compat with tests / external consumers that still +# import them from this module. New code should import from +# apm_cli.integration.copilot_app_workflow_integrator directly. +# --------------------------------------------------------------------------- - hour = meta.get("schedule_hour", 9) - if not isinstance(hour, int) or not (0 <= hour <= 23): - raise ValueError(f"schedule_hour must be int 0..23, got {hour!r}") - - day = meta.get("schedule_day", 1) - if not isinstance(day, int) or not (0 <= day <= 6): - raise ValueError(f"schedule_day must be int 0..6, got {day!r}") - - mode = meta.get("mode") - if mode is not None: - mode = str(mode) - if mode == "autopilot": - raise ValueError( - "mode 'autopilot' is not accepted via apm install -- " - "APM does not deploy workflows on autopilot. " - "Set autopilot manually in the Copilot App after enabling the row." - ) - if mode not in _VALID_SCHEDULE_MODES: - raise ValueError(f"mode must be one of {sorted(_VALID_SCHEDULE_MODES)}, got {mode!r}") - - model = meta.get("model") - if model is not None and not isinstance(model, str): - raise ValueError(f"model must be a string, got {model!r}") - - reasoning_effort = meta.get("reasoning_effort") - if reasoning_effort is not None and not isinstance(reasoning_effort, str): - raise ValueError(f"reasoning_effort must be a string, got {reasoning_effort!r}") - - return Schedule( - interval=interval, - schedule_hour=hour, - schedule_day=day, - mode=mode, - model=model, - reasoning_effort=reasoning_effort, - ) - - -# Back-compat alias retained for test imports; new code should use -# ``_parse_workflow_frontmatter`` directly. -_parse_schedule = _parse_workflow_frontmatter - - -def _derive_package_owner(package_info) -> str: - """Best-effort owner-segment extraction for namespacing workflow ids. - - Looks at the package's ``source`` (GitHub-style ``owner/repo`` or - URL) first, then ``author``, then falls back to ``"local"`` for - locally-sourced packages. The returned string is slugified by the - DB-side ``namespaced_id`` helper, so any input is safe. - """ - pkg = package_info.package - source = getattr(pkg, "source", None) - if isinstance(source, str) and source: - # github:foo/bar, https://github.com/foo/bar, foo/bar - s = source.split("://", 1)[-1] - s = s.split(":", 1)[-1] - parts = [p for p in s.split("/") if p and p != "github.com"] - if parts: - return parts[0] - author = getattr(pkg, "author", None) - if isinstance(author, str) and author.strip(): - return author.strip() - return "local" +from apm_cli.integration.copilot_app_workflow_integrator import ( # noqa: E402 + Schedule, + _derive_package_owner, + _is_workflow_shape, + _parse_schedule, + _parse_workflow_frontmatter, +) + +__all__ = [ + "PromptIntegrator", + "Schedule", + "_derive_package_owner", + "_is_workflow_shape", + "_parse_schedule", + "_parse_workflow_frontmatter", +] diff --git a/tests/unit/integration/test_copilot_app_error_ux.py b/tests/unit/integration/test_copilot_app_error_ux.py index 657b6f247d..cef109d8d0 100644 --- a/tests/unit/integration/test_copilot_app_error_ux.py +++ b/tests/unit/integration/test_copilot_app_error_ux.py @@ -138,10 +138,13 @@ def boom(*_args, **_kwargs): assert result.files_integrated == 0 assert result.files_skipped == 2 - # Two diagnostics, one per prompt, each carrying the original - # message so the user has something actionable. - assert len(diags.warns) == 2 - for entry in diags.warns: + # Two per-prompt deploy diagnostics, each carrying the original + # message so the user has something actionable. (An additional + # "no git repo detected" warn fires once for the whole install + # because tmp_path is not a git working tree -- filter it out.) + deploy_warns = [w for w in diags.warns if expected_substring in w["message"]] + assert len(deploy_warns) == 2 + for entry in deploy_warns: assert entry["package"] == "demo-pkg" assert "Copilot App" in entry["message"] assert expected_substring in entry["message"] @@ -175,8 +178,12 @@ def flaky(*_args, **_kwargs): assert result.files_integrated == 1 assert result.files_skipped == 1 - assert len(diags.warns) == 1 - assert "transient lock" in diags.warns[0]["message"] + # One deploy warn for the transient lock; an additional "no git + # repo detected" warn fires once because tmp_path is not a git + # working tree -- filter it out. + deploy_warns = [w for w in diags.warns if "transient lock" in w["message"]] + assert len(deploy_warns) == 1 + assert "transient lock" in deploy_warns[0]["message"] def test_missing_db_resolver_returns_empty_no_exception( self, From b6f6a9407436859a03b771f538e8897960c6da01 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Thu, 21 May 2026 22:12:16 +0200 Subject: [PATCH 10/10] fix(copilot-app): dedupe DB write-prelude + add websockets NOTICE entry - Extract _open_write_txn() helper in copilot_app_db so both deploy_workflow and copilot_app_project.resolve_or_register_project share the missing-DB / version-guard / BEGIN-IMMEDIATE prelude. Closes the pylint R0801 duplicate-code finding without changing behavior or error wording. - Drop the now-unused _connect / _check_user_version / _begin_immediate_with_retry imports from copilot_app_project. - Update test_race_collision_resolves_to_winning_id to patch copilot_app_db._connect (the real entry point) rather than the project module re-export, which is gone. - Add websockets entry to scripts/notice-metadata.yaml and regenerate NOTICE so the drift check passes for the new runtime dependency. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- NOTICE | 40 ++++ scripts/notice-metadata.yaml | 6 + src/apm_cli/integration/copilot_app_db.py | 196 ++++++++++-------- .../integration/copilot_app_project.py | 119 +++++------ .../integration/test_copilot_app_project.py | 8 +- 5 files changed, 213 insertions(+), 156 deletions(-) diff --git a/NOTICE b/NOTICE index 828c17e75f..23a264c145 100644 --- a/NOTICE +++ b/NOTICE @@ -1252,6 +1252,46 @@ SOFTWARE. --- +## Component. websockets + +- Version requirement: `>=12,<17` +- Upstream: https://github.com/python-websockets/websockets +- SPDX: `BSD-3-Clause` +- Notes: Used by the copilot-app integrator to nudge the Copilot desktop App over its local WebSocket IPC channel after writing workflows to the App DB. + +### Open Source License/Copyright Notice. + +_Copyright (c) Aymeric Augustin and contributors_ + +``` +Copyright (c) Aymeric Augustin and contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +--- + Submitted on behalf of a third-party The contributions below are identified as submitted on behalf of a diff --git a/scripts/notice-metadata.yaml b/scripts/notice-metadata.yaml index b9c838a00c..a2ea43c1b9 100644 --- a/scripts/notice-metadata.yaml +++ b/scripts/notice-metadata.yaml @@ -277,3 +277,9 @@ components: spdx: MIT copyright_snippet: Copyright (c) 2014-2026 Anthon van der Neut, Ruamel bvba notes: Canonical source is SourceForge (Mercurial). LICENSE retrieved from the official PyPI sdist tarball ruamel_yaml-0.19.1.tar.gz. + - name: websockets + pyproject_name: websockets + upstream: https://github.com/python-websockets/websockets + spdx: BSD-3-Clause + copyright_snippet: Copyright (c) Aymeric Augustin and contributors + notes: Used by the copilot-app integrator to nudge the Copilot desktop App over its local WebSocket IPC channel after writing workflows to the App DB. diff --git a/src/apm_cli/integration/copilot_app_db.py b/src/apm_cli/integration/copilot_app_db.py index 75b77d55b4..2f026e2487 100644 --- a/src/apm_cli/integration/copilot_app_db.py +++ b/src/apm_cli/integration/copilot_app_db.py @@ -369,6 +369,40 @@ def _begin_immediate_with_retry(conn: sqlite3.Connection) -> None: # --------------------------------------------------------------------------- +def _open_write_txn(db_path: Path) -> sqlite3.Connection: + """Resolve the App DB and open a write transaction, or raise. + + Centralizes the prelude shared by every writer in this package + (and by ``copilot_app_project.resolve_or_register_project``): + + 1. Refuse if ``db_path`` does not exist (``CopilotAppDbMissingError``). + 2. Open a fresh connection via ``_connect``. + 3. Verify the schema is in range via ``_check_user_version``. + 4. Acquire a write lock via ``_begin_immediate_with_retry``. + + On any failure during steps 3 / 4 the connection is closed before + the exception propagates. The caller owns the connection on success + and MUST ``COMMIT`` / ``ROLLBACK`` + ``close()``. + + Extracted to satisfy the repo's R0801 duplicate-code guardrail and + to keep the missing-DB error wording identical across writers. + """ + if not db_path.is_file(): + raise CopilotAppDbMissingError( + f"Copilot App database not found at {db_path}. " + f"Install the GitHub Copilot desktop app, or omit " + f"'--target copilot-app'." + ) + conn = _connect(db_path) + try: + _check_user_version(conn) + _begin_immediate_with_retry(conn) + except Exception: + conn.close() + raise + return conn + + def _validate_row(row: WorkflowRow) -> None: """Pre-write sanity check on a ``WorkflowRow`` we are about to store. @@ -425,42 +459,72 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: ValueError: ``row`` fails ``_validate_row``. """ _validate_row(row) - if not db_path.is_file(): - raise CopilotAppDbMissingError( - f"Copilot App database not found at {db_path}. " - f"Install the GitHub Copilot desktop app, or omit " - f"'--target copilot-app'." - ) - - conn = _connect(db_path) + conn = _open_write_txn(db_path) try: - _check_user_version(conn) - _begin_immediate_with_retry(conn) - try: - existing = conn.execute( + existing = conn.execute( + """ + SELECT prompt, mode, interval, schedule_hour, schedule_day, + model, reasoning_effort + FROM workflows WHERE id = ? + """, + (row.id,), + ).fetchone() + if existing is None: + # INSERT always writes enabled=0 regardless of row.enabled. + # The user must opt in via the App UI -- a third-party package + # cannot auto-run on install even if a future caller passes + # enabled=1 to this writer. Defence in depth alongside the + # caller-side enforcement in PromptIntegrator. + conn.execute( """ - SELECT prompt, mode, interval, schedule_hour, schedule_day, - model, reasoning_effort - FROM workflows WHERE id = ? + INSERT INTO workflows ( + id, name, prompt, model, reasoning_effort, + interval, schedule_hour, schedule_day, + enabled, mode, project_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?) """, - (row.id,), - ).fetchone() - if existing is None: - # INSERT always writes enabled=0 regardless of row.enabled. - # The user must opt in via the App UI -- a third-party package - # cannot auto-run on install even if a future caller passes - # enabled=1 to this writer. Defence in depth alongside the - # caller-side enforcement in PromptIntegrator. + ( + row.id, + row.name, + row.prompt, + row.model, + row.reasoning_effort, + row.interval, + row.schedule_hour, + row.schedule_day, + row.mode, + row.project_id, + ), + ) + else: + execution_changed = ( + existing["prompt"] != row.prompt + or existing["mode"] != row.mode + or existing["interval"] != row.interval + or existing["schedule_hour"] != row.schedule_hour + or existing["schedule_day"] != row.schedule_day + or existing["model"] != row.model + or existing["reasoning_effort"] != row.reasoning_effort + ) + if execution_changed: conn.execute( """ - INSERT INTO workflows ( - id, name, prompt, model, reasoning_effort, - interval, schedule_hour, schedule_day, - enabled, mode, project_id - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?) + UPDATE workflows + SET name = ?, + prompt = ?, + model = ?, + reasoning_effort = ?, + interval = ?, + schedule_hour = ?, + schedule_day = ?, + mode = ?, + project_id = ?, + enabled = 0, + next_run_at = NULL, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE id = ? """, ( - row.id, row.name, row.prompt, row.model, @@ -470,67 +534,27 @@ def deploy_workflow(db_path: Path, row: WorkflowRow) -> str: row.schedule_day, row.mode, row.project_id, + row.id, ), ) else: - execution_changed = ( - existing["prompt"] != row.prompt - or existing["mode"] != row.mode - or existing["interval"] != row.interval - or existing["schedule_hour"] != row.schedule_hour - or existing["schedule_day"] != row.schedule_day - or existing["model"] != row.model - or existing["reasoning_effort"] != row.reasoning_effort + # Self-heal pre-PR-A rows: even when nothing else + # changed, stamp project_id so a NULL left by an + # older APM install is filled on the next run. + conn.execute( + """ + UPDATE workflows + SET name = ?, + project_id = ?, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE id = ? + """, + (row.name, row.project_id, row.id), ) - if execution_changed: - conn.execute( - """ - UPDATE workflows - SET name = ?, - prompt = ?, - model = ?, - reasoning_effort = ?, - interval = ?, - schedule_hour = ?, - schedule_day = ?, - mode = ?, - project_id = ?, - enabled = 0, - next_run_at = NULL, - updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') - WHERE id = ? - """, - ( - row.name, - row.prompt, - row.model, - row.reasoning_effort, - row.interval, - row.schedule_hour, - row.schedule_day, - row.mode, - row.project_id, - row.id, - ), - ) - else: - # Self-heal pre-PR-A rows: even when nothing else - # changed, stamp project_id so a NULL left by an - # older APM install is filled on the next run. - conn.execute( - """ - UPDATE workflows - SET name = ?, - project_id = ?, - updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') - WHERE id = ? - """, - (row.name, row.project_id, row.id), - ) - conn.execute("COMMIT") - except Exception: - conn.execute("ROLLBACK") - raise + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise finally: conn.close() diff --git a/src/apm_cli/integration/copilot_app_project.py b/src/apm_cli/integration/copilot_app_project.py index d6bbcb7424..ea0c77351b 100644 --- a/src/apm_cli/integration/copilot_app_project.py +++ b/src/apm_cli/integration/copilot_app_project.py @@ -43,10 +43,7 @@ from apm_cli.integration.copilot_app_db import ( CopilotAppDbError, - CopilotAppDbMissingError, - _begin_immediate_with_retry, - _check_user_version, - _connect, + _open_write_txn, ) # --------------------------------------------------------------------------- @@ -343,75 +340,65 @@ def resolve_or_register_project_sqlite( (delegated to ``_check_user_version``). CopilotAppDbLockedError: ``BEGIN IMMEDIATE`` timed out. """ - if not db_path.is_file(): - raise CopilotAppDbMissingError( - f"Copilot App database not found at {db_path}. " - f"Install the GitHub Copilot desktop app, or omit " - f"'--target copilot-app'." - ) - - conn = _connect(db_path) + conn = _open_write_txn(db_path) try: - _check_user_version(conn) - _begin_immediate_with_retry(conn) + existing = conn.execute( + "SELECT id, main_repo_path FROM projects WHERE main_repo_path = ?", + (str(ctx.repo_root),), + ).fetchone() + if existing is not None: + conn.execute("COMMIT") + return ResolvedProject( + project_id=existing["id"], + was_created=False, + main_repo_path=existing["main_repo_path"], + ) + + recipe = derive_project_recipe(ctx) try: - existing = conn.execute( + conn.execute( + _PROJECTS_INSERT_SQL, + ( + recipe.id, + recipe.name, + recipe.main_repo_path, + recipe.default_branch, + recipe.github_owner, + recipe.github_repo, + ), + ) + except sqlite3.IntegrityError: + # Race: another writer (the App itself, or a parallel + # apm install) inserted the same main_repo_path between + # our SELECT and INSERT. Re-read inside this transaction + # to find the winner's id. + row = conn.execute( "SELECT id, main_repo_path FROM projects WHERE main_repo_path = ?", (str(ctx.repo_root),), ).fetchone() - if existing is not None: - conn.execute("COMMIT") - return ResolvedProject( - project_id=existing["id"], - was_created=False, - main_repo_path=existing["main_repo_path"], - ) - - recipe = derive_project_recipe(ctx) - try: - conn.execute( - _PROJECTS_INSERT_SQL, - ( - recipe.id, - recipe.name, - recipe.main_repo_path, - recipe.default_branch, - recipe.github_owner, - recipe.github_repo, - ), - ) - except sqlite3.IntegrityError: - # Race: another writer (the App itself, or a parallel - # apm install) inserted the same main_repo_path between - # our SELECT and INSERT. Re-read inside this transaction - # to find the winner's id. - row = conn.execute( - "SELECT id, main_repo_path FROM projects WHERE main_repo_path = ?", - (str(ctx.repo_root),), - ).fetchone() - if row is None: - # IntegrityError but no matching row -- some other - # constraint failed (e.g. NOT NULL on a column we - # don't write). Surface as a DB error. - raise CopilotAppDbError( - "Race recovery failed: project row INSERT collided " - "but no matching row was found post-collision." - ) from None - conn.execute("COMMIT") - return ResolvedProject( - project_id=row["id"], - was_created=False, - main_repo_path=row["main_repo_path"], - ) - + if row is None: + # IntegrityError but no matching row -- some other + # constraint failed (e.g. NOT NULL on a column we + # don't write). Surface as a DB error. + raise CopilotAppDbError( + "Race recovery failed: project row INSERT collided " + "but no matching row was found post-collision." + ) from None conn.execute("COMMIT") return ResolvedProject( - project_id=recipe.id, - was_created=True, - main_repo_path=recipe.main_repo_path, + project_id=row["id"], + was_created=False, + main_repo_path=row["main_repo_path"], ) - except Exception: - conn.execute("ROLLBACK") - raise + + conn.execute("COMMIT") + return ResolvedProject( + project_id=recipe.id, + was_created=True, + main_repo_path=recipe.main_repo_path, + ) + except Exception: + conn.execute("ROLLBACK") + raise finally: conn.close() diff --git a/tests/unit/integration/test_copilot_app_project.py b/tests/unit/integration/test_copilot_app_project.py index ec3cac86a4..c63a128270 100644 --- a/tests/unit/integration/test_copilot_app_project.py +++ b/tests/unit/integration/test_copilot_app_project.py @@ -272,8 +272,8 @@ def test_race_collision_resolves_to_winning_id( ) -> None: """Simulate concurrent INSERT mid-transaction. - Captures the connection the resolver opens via ``_connect``, then - monkeypatches ``derive_project_recipe`` (called between SELECT + Captures the connection the resolver opens via ``cdb._connect``, + then monkeypatches ``derive_project_recipe`` (called between SELECT and INSERT) to insert a colliding row on the SAME connection so the resolver's INSERT trips ``sqlite3.IntegrityError`` and falls into the race-recovery SELECT branch. @@ -283,14 +283,14 @@ def test_race_collision_resolves_to_winning_id( winning_id = "11111111-2222-4333-8444-555555555555" captured: dict[str, sqlite3.Connection] = {} - real_connect = cap._connect + real_connect = cdb._connect def capturing_connect(path): conn = real_connect(path) captured["c"] = conn return conn - monkeypatch.setattr(cap, "_connect", capturing_connect) + monkeypatch.setattr(cdb, "_connect", capturing_connect) real_derive = cap.derive_project_recipe