diff --git a/config/scripts/orchestration-skill-guidance.test.mjs b/config/scripts/orchestration-skill-guidance.test.mjs index 2ed4288e223..bb2b6c30027 100644 --- a/config/scripts/orchestration-skill-guidance.test.mjs +++ b/config/scripts/orchestration-skill-guidance.test.mjs @@ -184,11 +184,16 @@ describe('orchestration kernel', () => { ) }) - it('names --terminal, never --from, as the check caller flag', () => { + it('resolves the check caller from the environment and never teaches naming another', () => { const kernel = squash(readKernel()) - expect(kernel).toContain('`check` names its caller with `--terminal `, never `--from`') + expect(kernel).toContain( + '`check` takes its caller from the environment in a chat or Orca terminal; elsewhere pass your own `--terminal `, never `--from`' + ) + expect(kernel).toContain('Never name another agent with `--from`/`--terminal`') expect(kernel).not.toContain('check --from') + // The #21097 shape: an instruction to name the caller by handle on every check. + expect(kernel).not.toContain('check --terminal ') }) it('makes a dispatched worker read coordinator follow-ups on a cadence', () => { @@ -196,7 +201,7 @@ describe('orchestration kernel', () => { expect(kernel).toContain('Read coordinator follow-ups at each natural checkpoint') expect(kernel).toContain('once more immediately before `worker_done`') - expect(kernel).toContain('`ORCA orchestration check --terminal --json`') + expect(kernel).toContain("with the preamble's own `check` command") }) it('requires full Delivery processing and settled-terminal accounting before ack', () => { diff --git a/resources/skills/current-manifest.json b/resources/skills/current-manifest.json index c0c492a2736..acfa1ed768d 100644 --- a/resources/skills/current-manifest.json +++ b/resources/skills/current-manifest.json @@ -5,17 +5,17 @@ "name": "computer-use", "sourcePath": "skills/computer-use", "releaseRevision": 9, - "packageDigest": "425634e3ebf27690cc613eaf17b6337b36769153ec6bca85dc4ebf65d4d6b8b4", - "gitTreeSha": "b59f27370a41225c22127e91da0c91cd2519f217", + "packageDigest": "a87375ac9e9250161fd73465c82364a865607aa0f5d90dee0d206293a5f1be53", + "gitTreeSha": "c1c110c2f328e9d97dc949f84fb6b325b73899de", "files": [ { "path": "SKILL.md", - "size": 2211, + "size": 2443, "executable": false, "classification": "text", - "exactSha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3", - "textNormalizedSha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3", - "identitySha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3" + "exactSha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486", + "textNormalizedSha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486", + "identitySha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486" } ] }, @@ -23,17 +23,17 @@ "name": "linear-tickets", "sourcePath": "skills/linear-tickets", "releaseRevision": 11, - "packageDigest": "1eab442d048b79ab0b836adf57663ac384988dd79172ec5f14193eb05e037715", - "gitTreeSha": "30d9b40144d4a9a07ce12f0d1a9261fd9cf9649b", + "packageDigest": "02af6f3804d3184c16c80bacbd7e241cf4df7ba2c9b6c4c9974e84cfaef37ddc", + "gitTreeSha": "754c4849a3ca79574dcb37aab4ca1836811bf8e9", "files": [ { "path": "SKILL.md", - "size": 2231, + "size": 2463, "executable": false, "classification": "text", - "exactSha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619", - "textNormalizedSha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619", - "identitySha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619" + "exactSha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab", + "textNormalizedSha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab", + "identitySha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab" } ] }, @@ -41,17 +41,17 @@ "name": "orca-cli", "sourcePath": "skills/orca-cli", "releaseRevision": 37, - "packageDigest": "0736bcbbb69ed18f9a36a58ad2eda47b6db55b30509953cf5ba5f0032058c535", - "gitTreeSha": "572f7952ac451a30a9c2451b472a639b125ee584", + "packageDigest": "bdc0bbb1899b27a05eeb8fea6e3f1b234eb2eaa7685dfb848adcf1740a7223e8", + "gitTreeSha": "a9b4f439f75db5de948128a4366a648c0e957a3c", "files": [ { "path": "SKILL.md", - "size": 2372, + "size": 2604, "executable": false, "classification": "text", - "exactSha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a", - "textNormalizedSha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a", - "identitySha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a" + "exactSha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe", + "textNormalizedSha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe", + "identitySha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe" } ] }, @@ -59,17 +59,17 @@ "name": "orca-emulator", "sourcePath": "skills/orca-emulator", "releaseRevision": 8, - "packageDigest": "1dc42e5addc613abd85eba639d4ac36d9c7b3bc6f7186f0a2d54d10dae3f06d3", - "gitTreeSha": "110f6ab59bd73428d7de28bd4761d1fc332efa20", + "packageDigest": "0be86ec897b1a9dbf144e823a4acf0d989ccce87bc251539626a2912e2bb7de9", + "gitTreeSha": "98ef2478491db03fcb04bcbb186e071ea44ead66", "files": [ { "path": "SKILL.md", - "size": 2337, + "size": 2569, "executable": false, "classification": "text", - "exactSha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48", - "textNormalizedSha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48", - "identitySha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48" + "exactSha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac", + "textNormalizedSha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac", + "identitySha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac" } ] }, @@ -77,17 +77,17 @@ "name": "orca-emulator-android", "sourcePath": "skills/orca-emulator-android", "releaseRevision": 6, - "packageDigest": "c348091d953427fc9800a1d49d94054866348008766879b24ef742cb613dc3d9", - "gitTreeSha": "437ed5e35698ee6421386a5a08fe7f8c7cf1a2a7", + "packageDigest": "52fa8998e9b3d0f5498c8f536f08d87c7719df177dbb0568af4611eb6139cdd5", + "gitTreeSha": "a17259cd07ac05a15059bafeca6088befd4e7f41", "files": [ { "path": "SKILL.md", - "size": 2234, + "size": 2466, "executable": false, "classification": "text", - "exactSha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278", - "textNormalizedSha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278", - "identitySha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278" + "exactSha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298", + "textNormalizedSha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298", + "identitySha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298" } ] }, @@ -95,17 +95,17 @@ "name": "orca-linear", "sourcePath": "skills/orca-linear", "releaseRevision": 9, - "packageDigest": "95f52429823e887317046f23b671d05408a947c296e5b2e44e9173dfc1d5aa4e", - "gitTreeSha": "8e747165847651926ca54804b012689ebcbd9432", + "packageDigest": "86e626833901186c2a15f0062b54fdebb7ac9124f91a087841adcee33f33a408", + "gitTreeSha": "e16fcb62227c392fdfa352982798089743edd870", "files": [ { "path": "SKILL.md", - "size": 2088, + "size": 2320, "executable": false, "classification": "text", - "exactSha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f", - "textNormalizedSha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f", - "identitySha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f" + "exactSha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888", + "textNormalizedSha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888", + "identitySha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888" } ] }, @@ -113,17 +113,17 @@ "name": "orca-per-workspace-env", "sourcePath": "skills/orca-per-workspace-env", "releaseRevision": 6, - "packageDigest": "103f0671da111c9ad3def6c46da8d432e656878b840e6cc742219f4a3a4dbceb", - "gitTreeSha": "58dfb5dc3ad287a6a42625f9d15c7c0c3dfd02ec", + "packageDigest": "321c1c4e08c4d93999db82ecd4d7b9a5f82653bf92aedc25faae066cca66ef13", + "gitTreeSha": "685470ac47e6402a9a3bec39df0f61ef82b4ebfe", "files": [ { "path": "SKILL.md", - "size": 2257, + "size": 2489, "executable": false, "classification": "text", - "exactSha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce", - "textNormalizedSha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce", - "identitySha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce" + "exactSha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56", + "textNormalizedSha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56", + "identitySha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56" } ] }, @@ -131,17 +131,17 @@ "name": "orchestration", "sourcePath": "skills/orchestration", "releaseRevision": 29, - "packageDigest": "195f26431ecfb6df41b941b22958a2330b110bac7b7e97004e0b35fe586e41d9", - "gitTreeSha": "b0cd1d58b0c317cf7c3726fef7e6b1197c405246", + "packageDigest": "85027b6598f0a6a99ed1267288574fec4b312372d9ef24ff4ee0bf3b51265c28", + "gitTreeSha": "1f31942ad58c785d917954c1bb3245f2278dac0a", "files": [ { "path": "SKILL.md", - "size": 3671, + "size": 3903, "executable": false, "classification": "text", - "exactSha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a", - "textNormalizedSha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a", - "identitySha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a" + "exactSha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002", + "textNormalizedSha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002", + "identitySha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002" } ] } diff --git a/resources/skills/snapshot-registry.json b/resources/skills/snapshot-registry.json index 731d0a85c8e..80309e533f6 100644 --- a/resources/skills/snapshot-registry.json +++ b/resources/skills/snapshot-registry.json @@ -580,17 +580,17 @@ }, { "releaseRevision": 37, - "packageDigest": "0736bcbbb69ed18f9a36a58ad2eda47b6db55b30509953cf5ba5f0032058c535", - "gitTreeSha": "572f7952ac451a30a9c2451b472a639b125ee584", + "packageDigest": "bdc0bbb1899b27a05eeb8fea6e3f1b234eb2eaa7685dfb848adcf1740a7223e8", + "gitTreeSha": "a9b4f439f75db5de948128a4366a648c0e957a3c", "files": [ { "path": "SKILL.md", - "size": 2372, + "size": 2604, "executable": false, "classification": "text", - "exactSha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a", - "textNormalizedSha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a", - "identitySha256": "aa76f86505010096e8ea9edda1705a78aae7af45e54485f3fe0460664c1d9e4a" + "exactSha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe", + "textNormalizedSha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe", + "identitySha256": "6797ddc4688ece98ff395b798b26b6a6dfe43130f13fbe0c56c37929400d2ffe" } ] } @@ -1046,17 +1046,17 @@ }, { "releaseRevision": 29, - "packageDigest": "195f26431ecfb6df41b941b22958a2330b110bac7b7e97004e0b35fe586e41d9", - "gitTreeSha": "b0cd1d58b0c317cf7c3726fef7e6b1197c405246", + "packageDigest": "85027b6598f0a6a99ed1267288574fec4b312372d9ef24ff4ee0bf3b51265c28", + "gitTreeSha": "1f31942ad58c785d917954c1bb3245f2278dac0a", "files": [ { "path": "SKILL.md", - "size": 3671, + "size": 3903, "executable": false, "classification": "text", - "exactSha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a", - "textNormalizedSha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a", - "identitySha256": "cd1b364bf35781bad06bf75ab1766afa8d6cec69cb2060529691d89871a2098a" + "exactSha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002", + "textNormalizedSha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002", + "identitySha256": "2832ac8b590f64823ceb1fb6c06c82dbfa02175ed16b0b5b69788bedf5a61002" } ] } @@ -1210,17 +1210,17 @@ }, { "releaseRevision": 9, - "packageDigest": "425634e3ebf27690cc613eaf17b6337b36769153ec6bca85dc4ebf65d4d6b8b4", - "gitTreeSha": "b59f27370a41225c22127e91da0c91cd2519f217", + "packageDigest": "a87375ac9e9250161fd73465c82364a865607aa0f5d90dee0d206293a5f1be53", + "gitTreeSha": "c1c110c2f328e9d97dc949f84fb6b325b73899de", "files": [ { "path": "SKILL.md", - "size": 2211, + "size": 2443, "executable": false, "classification": "text", - "exactSha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3", - "textNormalizedSha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3", - "identitySha256": "2839933fd35216845461466403e6061488005f6df57126d0cd0f769ea45753f3" + "exactSha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486", + "textNormalizedSha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486", + "identitySha256": "f5b644888461f1589fd20b03b38f6f3aafcd12d1102c346a63cfb76fd193b486" } ] } @@ -1340,17 +1340,17 @@ }, { "releaseRevision": 8, - "packageDigest": "1dc42e5addc613abd85eba639d4ac36d9c7b3bc6f7186f0a2d54d10dae3f06d3", - "gitTreeSha": "110f6ab59bd73428d7de28bd4761d1fc332efa20", + "packageDigest": "0be86ec897b1a9dbf144e823a4acf0d989ccce87bc251539626a2912e2bb7de9", + "gitTreeSha": "98ef2478491db03fcb04bcbb186e071ea44ead66", "files": [ { "path": "SKILL.md", - "size": 2337, + "size": 2569, "executable": false, "classification": "text", - "exactSha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48", - "textNormalizedSha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48", - "identitySha256": "3da7191179e46cb0e1a6a936f1eb54254f6e98ec38849e1c95f0e11073076b48" + "exactSha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac", + "textNormalizedSha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac", + "identitySha256": "9a42e901ee282eb11ca17e854d4ec8ce26dbc0f70175f5cba582c76de48546ac" } ] } @@ -1518,17 +1518,17 @@ }, { "releaseRevision": 11, - "packageDigest": "1eab442d048b79ab0b836adf57663ac384988dd79172ec5f14193eb05e037715", - "gitTreeSha": "30d9b40144d4a9a07ce12f0d1a9261fd9cf9649b", + "packageDigest": "02af6f3804d3184c16c80bacbd7e241cf4df7ba2c9b6c4c9974e84cfaef37ddc", + "gitTreeSha": "754c4849a3ca79574dcb37aab4ca1836811bf8e9", "files": [ { "path": "SKILL.md", - "size": 2231, + "size": 2463, "executable": false, "classification": "text", - "exactSha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619", - "textNormalizedSha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619", - "identitySha256": "e181f86073da65c492361469d504fe15e7ae61bc99990bc41bea47aa13455619" + "exactSha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab", + "textNormalizedSha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab", + "identitySha256": "cbf6afd89607bf8c5af9dd3dd20363e65108291d0d5a43e5b1d0fcaed9bbf9ab" } ] } @@ -1664,17 +1664,17 @@ }, { "releaseRevision": 9, - "packageDigest": "95f52429823e887317046f23b671d05408a947c296e5b2e44e9173dfc1d5aa4e", - "gitTreeSha": "8e747165847651926ca54804b012689ebcbd9432", + "packageDigest": "86e626833901186c2a15f0062b54fdebb7ac9124f91a087841adcee33f33a408", + "gitTreeSha": "e16fcb62227c392fdfa352982798089743edd870", "files": [ { "path": "SKILL.md", - "size": 2088, + "size": 2320, "executable": false, "classification": "text", - "exactSha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f", - "textNormalizedSha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f", - "identitySha256": "8da23ef96470906315cace8ff84f8056255ee37d1b2d5db84d8b7b3270a0ba0f" + "exactSha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888", + "textNormalizedSha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888", + "identitySha256": "ade35a188703c61d3f7ef7d536f89b42be7cc5e8cca14972c3f749fabeebb888" } ] } @@ -1762,17 +1762,17 @@ }, { "releaseRevision": 6, - "packageDigest": "c348091d953427fc9800a1d49d94054866348008766879b24ef742cb613dc3d9", - "gitTreeSha": "437ed5e35698ee6421386a5a08fe7f8c7cf1a2a7", + "packageDigest": "52fa8998e9b3d0f5498c8f536f08d87c7719df177dbb0568af4611eb6139cdd5", + "gitTreeSha": "a17259cd07ac05a15059bafeca6088befd4e7f41", "files": [ { "path": "SKILL.md", - "size": 2234, + "size": 2466, "executable": false, "classification": "text", - "exactSha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278", - "textNormalizedSha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278", - "identitySha256": "3ade4e6f8f2717ca899fd841e61f116963a406e9527015b803854c16d012e278" + "exactSha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298", + "textNormalizedSha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298", + "identitySha256": "21e679811789903da8c776e4239dc681b0db8641ee59158ae3aa30b936fff298" } ] } @@ -1860,17 +1860,17 @@ }, { "releaseRevision": 6, - "packageDigest": "103f0671da111c9ad3def6c46da8d432e656878b840e6cc742219f4a3a4dbceb", - "gitTreeSha": "58dfb5dc3ad287a6a42625f9d15c7c0c3dfd02ec", + "packageDigest": "321c1c4e08c4d93999db82ecd4d7b9a5f82653bf92aedc25faae066cca66ef13", + "gitTreeSha": "685470ac47e6402a9a3bec39df0f61ef82b4ebfe", "files": [ { "path": "SKILL.md", - "size": 2257, + "size": 2489, "executable": false, "classification": "text", - "exactSha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce", - "textNormalizedSha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce", - "identitySha256": "c005d126a13d2913351472f07690f1c1a660d4f286e2a5f21864aee294f436ce" + "exactSha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56", + "textNormalizedSha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56", + "identitySha256": "9eee084101f5a41d697e95f91505539abca3b3c40203e04077771c6c134bff56" } ] } diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index a7d63ff922c..d92fb30205a 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -65,6 +65,8 @@ non-Orca subagent tool when Orca orchestration provenance was requested. - Use the executable you used to run `skills get` for the entire run. In the examples below, replace `ORCA` with it; do not create a shell variable or run `ORCA` literally. If it fails, report that exact error instead of switching. +- Your address is `caller.address` in `ORCA status --json`: `session:` in a + chat, your handle in a terminal. Never name another agent with `--from`/`--terminal`. - A successful `orchestration send` proves durable enqueue; its wake or nudge is best-effort attention only and does not prove the recipient read or accepted it. @@ -78,8 +80,8 @@ The injected preamble is authoritative. A dispatched worker must: 2. Send heartbeats only at the cadence in the preamble. A heartbeat proves liveness, not completion. 3. Read coordinator follow-ups at each natural checkpoint — before starting a - new file, after a test run — and once more immediately before `worker_done`: - `ORCA orchestration check --terminal --json`. + new file, after a test run — and once more immediately before `worker_done`, + with the preamble's own `check` command. 4. Send `worker_done` exactly once, from the dispatched terminal, with a three-sentence executive summary, both lifecycle IDs, and explicit `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose. @@ -112,11 +114,12 @@ dependencies or a retry of a known Task. Use dependencies only for real ordering and prefer parallel waves over chains deeper than three or four steps; nested workers obey the depth limit, and a new Run does not reset the caller's depth. -A consuming `check` names its caller with `--terminal `, never `--from`; -omit it inside the coordinator's own Orca terminal. It returns the bound Run's -oldest FIFO Delivery and replays that batch until acknowledged. Process every -message: reply to questions, validate each `worker_done` against the expected -active Dispatch, and decide each settled terminal's next owner before the ack: +A consuming `check` takes its caller from the environment in a chat or Orca +terminal; elsewhere pass your own `--terminal `, never `--from`. It +returns the bound Run's oldest FIFO Delivery and replays that batch until +acknowledged. Process every message: reply to questions, validate each +`worker_done` against the expected active Dispatch, and decide each settled +terminal's next owner before the ack: ```text ORCA orchestration reply --id --body "" --json @@ -140,7 +143,8 @@ worker's own observation of process exit, or a transcript whose final agent turn sent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose `worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence, including when `worker-show` reports `agentWait` null. Absence never authorizes -stop, abandon, retry, or release; keep waiting or inspect. +stop, abandon, retry, or release; keep waiting or inspect. A chat coordinator +ends its turn instead of `check --wait`; see `references/coordinator-loop.md`. `worker-start` is the normal path, composing placement, terminal readiness, prompt injection, and supervised resource ownership. `dispatch --inject` leaves @@ -185,7 +189,7 @@ older CLI rejects `--full`, keep this kernel's safety floor, use that command's | Action gate | Bundled reference | | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` | +| Chat coordination, expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` | | You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` | | New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` | | Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` | diff --git a/skill-guides/orchestration/references/coordinator-loop.md b/skill-guides/orchestration/references/coordinator-loop.md index aec13667645..96c0b421ae1 100644 --- a/skill-guides/orchestration/references/coordinator-loop.md +++ b/skill-guides/orchestration/references/coordinator-loop.md @@ -1,9 +1,30 @@ # Coordinator loop -Load this reference for expanded DAG waves, per-invocation launch preferences, -same-terminal reuse, or review ownership. The compact guide remains the source +Load this reference for coordinating from a chat session, expanded DAG waves, +per-invocation launch preferences, same-terminal reuse, or review ownership. The compact guide remains the source of truth for the loop order and completion boundary. +## Coordinating from a chat session + +When `ORCA status --json` reports `caller.kind` `session`, you coordinate from a +chat. Never block in `check --wait`: your shell tool has its own timeout, and +Orca wakes you instead. When messages reach your Run, Orca starts a new turn in +this chat once you are idle, saying `You have orchestration message(s)` and +naming the `check` to run. + +1. Bind one Run and start the full independent wave. +2. End your turn. +3. On each such turn run the `check` it names, without `--wait`. Process every + message as the compact guide requires, then acknowledge with + `ORCA orchestration check --ack --json`, which also returns the + next batch. Repeat until no Delivery is returned. +4. End your turn again. When every expected Dispatch has settled, report. + +A turn with no new Delivery is a checkpoint, not a failure. The compact guide's +empty-wait enumeration applies when a turn arrives and a Dispatch you expected +has still not settled. `/clear` gives the chat a new session and address; Orca +moves your Runs and unread mail to it. + ## Ready waves Create independent Tasks before the first wait. Encode only real dependencies, diff --git a/skill-guides/orchestration/references/messaging-and-gates.md b/skill-guides/orchestration/references/messaging-and-gates.md index 573ca90e5e7..bed3fc33f88 100644 --- a/skill-guides/orchestration/references/messaging-and-gates.md +++ b/skill-guides/orchestration/references/messaging-and-gates.md @@ -10,9 +10,11 @@ accepted steering. ## Coordinator delivery loop `check` names its caller with `--terminal ` and is the only verb that -rejects `--from`. Omit `--terminal` inside an Orca terminal, where Orca resolves -the caller; pass it explicitly from anywhere else, including a dispatched -worker reading coordinator follow-ups. +rejects `--from`. Omit `--terminal` in a chat session, whose caller is always +`session:`, and inside an Orca terminal, where Orca resolves the caller. +Pass your own handle explicitly from anywhere else, including a dispatched +worker reading coordinator follow-ups. A chat coordinator never waits: it +checks without `--wait` on each turn Orca starts for new mail. A consuming coordinator `check` returns the bound Run's oldest FIFO Delivery, up to 50 messages, and replays that exact batch until acknowledged. Process @@ -36,7 +38,14 @@ ORCA orchestration send --to dispatch: --subject "Follow-up" --body Do not substitute a remote terminal handle. Omit `--from` for ordinary coordinator calls; a dispatched worker instead copies the exact `--from` and -capability arguments in its preamble. `check` is the exception: it identifies +capability arguments in its preamble. Any live chat session on this host is +reachable at `session:`, its Orca session id, never the provider's id (it +changes on `/clear`). `ORCA status --json` reports your own as `caller.address`; +a `caller` with `live: false` carries the refusal that stops you acting as that +session, and `null` means the shell has no orchestration identity. A user may +copy a chat's address with its Copy Orchestration Address menu action. `/clear` +gives a chat a new address: Orca moves its Runs and unread mail there, and a +send to the old one is refused with the new one named. `check` is the exception: it identifies its caller with `--terminal`, never `--from`. Group addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, diff --git a/skill-stubs/_shared/cli-resolution.md b/skill-stubs/_shared/cli-resolution.md index 8c898be5ad6..dc5d238004f 100644 --- a/skill-stubs/_shared/cli-resolution.md +++ b/skill-stubs/_shared/cli-resolution.md @@ -7,7 +7,9 @@ Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/computer-use/SKILL.md b/skills/computer-use/SKILL.md index 8c89c613921..8abf2be8728 100644 --- a/skills/computer-use/SKILL.md +++ b/skills/computer-use/SKILL.md @@ -18,7 +18,9 @@ This discovery stub loads the version-matched guide from the Orca executable use Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/linear-tickets/SKILL.md b/skills/linear-tickets/SKILL.md index 86c9eba8285..109f7387435 100644 --- a/skills/linear-tickets/SKILL.md +++ b/skills/linear-tickets/SKILL.md @@ -19,7 +19,9 @@ This discovery stub uses the legacy name `linear-tickets` for `orca-linear`; bot Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orca-cli/SKILL.md b/skills/orca-cli/SKILL.md index fbea1b6566c..0f012670cdd 100644 --- a/skills/orca-cli/SKILL.md +++ b/skills/orca-cli/SKILL.md @@ -19,7 +19,9 @@ This discovery stub loads the version-matched guide from the Orca executable use Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orca-emulator-android/SKILL.md b/skills/orca-emulator-android/SKILL.md index 3754741f4ad..d4edcae7a7d 100644 --- a/skills/orca-emulator-android/SKILL.md +++ b/skills/orca-emulator-android/SKILL.md @@ -19,7 +19,9 @@ This discovery stub loads the version-matched guide from the Orca executable use Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orca-emulator/SKILL.md b/skills/orca-emulator/SKILL.md index 317182bfbae..b89a37538f3 100644 --- a/skills/orca-emulator/SKILL.md +++ b/skills/orca-emulator/SKILL.md @@ -22,7 +22,9 @@ handles device scoping, helper lifecycle, and worktree context. Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orca-linear/SKILL.md b/skills/orca-linear/SKILL.md index f70f55ca41e..7fa31063432 100644 --- a/skills/orca-linear/SKILL.md +++ b/skills/orca-linear/SKILL.md @@ -17,7 +17,9 @@ This discovery stub loads the version-matched guide from the Orca executable use Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orca-per-workspace-env/SKILL.md b/skills/orca-per-workspace-env/SKILL.md index ff37d027767..7686d539187 100644 --- a/skills/orca-per-workspace-env/SKILL.md +++ b/skills/orca-per-workspace-env/SKILL.md @@ -18,7 +18,9 @@ This discovery stub loads the version-matched guide from the Orca executable use Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/skills/orchestration/SKILL.md b/skills/orchestration/SKILL.md index 4ecd42624d4..785f1111433 100644 --- a/skills/orchestration/SKILL.md +++ b/skills/orchestration/SKILL.md @@ -30,7 +30,9 @@ state; never substitute a non-Orca subagent tool. Choose the executable once and reuse it for every later command: - If the `ORCA_CLI_COMMAND` environment variable is set, use its value. Orca exports this - for managed WSL sessions. + for managed WSL sessions and for its chat sessions, whose login shells (Codex's among + them) can put a different `orca` first on PATH. Invoke it as `"$ORCA_CLI_COMMAND"` in a + POSIX shell, Git Bash included, and as `& $env:ORCA_CLI_COMMAND` in PowerShell. - Otherwise, in a dev checkout whose session exposes `ORCA_DEV_REPO_ROOT`, use `orca-dev`. - Otherwise, on Linux outside an Orca-managed terminal, use `orca-ide`. Never run bare `orca` there — outside Orca's terminals it normally resolves to the diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 0985a2239ab..292f9bc3794 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -66,13 +66,13 @@ const ORCA_PER_WORKSPACE_ENV_SSH_HOST_REFERENCE_MARKDOWN = "# SSH connection mod const ORCA_PER_WORKSPACE_ENV_WINDOWS_SCRIPTS_REFERENCE_MARKDOWN = "# Windows local-side scripts\n\nLoad this when the user's desktop is Windows and you are scaffolding the local-side scripts. A bare\n`.sh` will not execute there. Either require WSL or Git Bash and point `orca.yaml` at a launcher such\nas `bash ./scripts/orca-vm/.sh` through a `.cmd` file, or scaffold PowerShell equivalents.\n\nThe remote-side commands you run inside the Linux environment stay bash regardless of the desktop OS.\n\n```powershell\n#requires -Version 5\n$ErrorActionPreference = 'Stop'\n# resolve env→state→fallback; run the provider CLI / ssh the same way;\n# capture provider output; build the result object for the chosen mode and write ONE line of JSON to stdout.\n# Orca-server mode: @{ schemaVersion=1; pairingCode=$pairingCode; projectRoot=$projectRoot; userData=@{...} }\n# SSH mode: @{ schemaVersion=1; connection=@{ type=\"ssh\"; projectRoot=$projectRoot;\n# target=@{ label=$label; host=$host; port=$port; username=$user } } }\n($result | ConvertTo-Json -Compress -Depth 6)\n# progress/errors → Write-Error / the error stream, never stdout.\n```\n\nThe doctor's executable-bit check is a POSIX concept and is skipped on Windows, so a script that is\nunusable on the user's machine for a different reason still has to be caught by the `--provision`\nself-test.\n" // oxfmt-ignore -const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, capability, Task ID, and Dispatch ID\n in the live preamble. Never reconstruct, translate, or broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`:\n `ORCA orchestration check --terminal --json`.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` names its caller with `--terminal `, never `--from`;\nomit it inside the coordinator's own Orca terminal. It returns the bound Run's\noldest FIFO Delivery and replays that batch until acknowledged. Process every\nmessage: reply to questions, validate each `worker_done` against the expected\nactive Dispatch, and decide each settled terminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n" +const ORCHESTRATION_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, capability, Task ID, and Dispatch ID\n in the live preamble. Never reconstruct, translate, or broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- Your address is `caller.address` in `ORCA status --json`: `session:` in a\n chat, your handle in a terminal. Never name another agent with `--from`/`--terminal`.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`,\n with the preamble's own `check` command.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` takes its caller from the environment in a chat or Orca\nterminal; elsewhere pass your own `--terminal `, never `--from`. It\nreturns the bound Run's oldest FIFO Delivery and replays that batch until\nacknowledged. Process every message: reply to questions, validate each\n`worker_done` against the expected active Dispatch, and decide each settled\nterminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect. A chat coordinator\nends its turn instead of `check --wait`; see `references/coordinator-loop.md`.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Chat coordination, expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n" // oxfmt-ignore -const ORCHESTRATION_FULL_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, capability, Task ID, and Dispatch ID\n in the live preamble. Never reconstruct, translate, or broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`:\n `ORCA orchestration check --terminal --json`.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` names its caller with `--terminal `, never `--from`;\nomit it inside the coordinator's own Orca terminal. It returns the bound Run's\noldest FIFO Delivery and replays that batch until acknowledged. Process every\nmessage: reply to questions, validate each `worker_done` against the expected\nactive Dispatch, and decide each settled terminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n\n---\n\n# Bundled references\n\nThese references belong to the version-matched guide above. Read only the documents named by its action gates.\n\n\n\n# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n\n\n\n# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n\n\n\n# Low-level topology\n\nLoad this reference only when `worker-start` cannot express required custom argv\nor terminal topology. It is not the normal supervised loop and is never a full\nhandoff recipe.\n\n```text\nORCA terminal create --worktree active --title --command \"\" --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\nORCA orchestration dispatch --task --to --inject --json\n```\n\nWait for readiness only when startup could lose injected input. Prefer\nagent-first `worker-start` whenever its argv and topology are sufficient.\n\n`dispatch --inject` creates authoritative Task/Dispatch context but deliberately\nkeeps an operator-created process unsupervised: it creates no supervised worker\nresource row. `worker-show`, `worker-read`, and `worker-list` report the lane as\n`unsupervised`; `worker-stop` and `worker-abandon` do not close that process, and\nsettled retain/release take no process action.\n\nUse `worker-start --terminal ` when lifecycle ownership of an existing\nagent terminal is required. Never imply that low-level dispatch retroactively\nowns a process, never use it to route around the nested-depth limit, and never\nuse it for an ownership handoff.\n\n\n\n# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` inside an Orca terminal, where Orca resolves\nthe caller; pass it explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\ncapability arguments in its preamble. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n\n\n\n# Placement and remote execution\n\nLoad this reference before creating a new worktree or placing work through SSH,\nWSL, or another connected Orca server.\n\n## Placement choices\n\nA fresh worker means a fresh agent terminal, not a new Git worktree. Use the\ncurrent or an exact existing workspace by default. Create a worktree only when\nthe user requested one or a concrete checkout or filesystem conflict makes\nsharing unsafe.\n\n```text\n# Current workspace; setup is not rerun.\nORCA orchestration worker-start --task --worktree current --agent codex --json\n\n# Stacked child worktree.\nORCA orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n\n# Independent top-level worktree.\nORCA orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nCurrent and exact existing workspaces create a fresh terminal unless\n`--terminal` is explicit. Folder workspaces are first-class; do not invoke Git\nor require worktree lineage when the selected workspace is a folder.\n\nRegister a folder workspace through project setup. `repo add --path `\nrequires a valid Git repository and rejects a plain directory:\n\n```text\nORCA project setup-existing-folder --project --host --path --kind folder --json\n```\n\nThen place work on the returned workspace with an exact selector. A worktree\nselector needs the full `::` value Orca returned, passed as\n`id:`; a bare repo id is not a worktree id. `new-child` and\n`new-top-level` are worktree creation and do not apply to a folder.\n\nNew worktrees use agent-first creation and run setup by default. Preserve the\nrepository's startup policy: `start-immediately` can report setup as `running`,\nwhile `wait-for-setup` gates prompt delivery on success. Orca lineage, Git base,\nfilesystem isolation, coordination parentage, UI grouping, and execution host\nare separate decisions.\n\n## Connected servers\n\nThe Run and Tasks remain authoritative on the current server. `--on` selects\nonly the worker's execution server and appears only on `worker-start`:\n\n```text\nORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run --json\n```\n\nRemote `current` and `new-child` are invalid because they are ambiguous across\nservers. Use an exact discovered remote workspace, or `new-top-level` with an\nexact remote repository selector. After start, route every follow-up, read,\nstop, and cleanup by Dispatch ID; never repeat `--on` or substitute a remote\nterminal handle.\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\nORCA orchestration worker-list --run --include-remote --json\n```\n\n`worker-list` reads local fleet state only; enumerate remote workers with\n`--include-remote` or every one of them reads `unverifiable`. Scope every list\nwith `--run `: unscoped, it reports every Dispatch this runtime has\nrecorded, and the workers you are waiting on are lost in that history.\n\n## Execution-host and mixed-version floor\n\nThe execution host owns process, filesystem, transcript, stop, and cleanup\nfacts. Render only `live`, `unverifiable`, or `exited`. Connection loss, relay\nabsence, missing client inventory, or timeout yields `unverifiable`, never\nsynthetic exit and never a client-local substitute action.\n\nClients and servers update independently. Optional response fields may be\nabsent. Forward model/effort, transcript reads, cleanup, or another new remote\noperation only when the peer advertises the relevant capability; unknown stream\nopcodes can be silently dropped. A narrow unsupported response may degrade to a\ndocumented older path, but must not broaden the target or cross the execution\nboundary. Changing host-published content reaches old clients even without a\nwire-shape change, so preserve established semantics or negotiate the behavior.\n\nFor WSL, use the exact executable and arguments returned by Orca so the distro\nand packaged launcher remain bound. Do not translate a printed `orca-ide`\nrecovery command into a PATH-resolved local command.\n\n\n\n# Recovery and cleanup\n\nLoad this reference only after a failed/stopped/unknown attempt, explicit retry\ndecision, stop/abandon request, retention request, or uncertain release.\n\n| Proven state | Safe action |\n| ----------------------- | ------------------------------------------------------------------ |\n| `ready` or active | Keep waiting; optionally read bounded output |\n| `failed` or `stopped` | Start a replacement with `--retry-of`; repeat placement explicitly |\n| `outcome_unknown` | Inspect, then choose `worker-stop` or explicit `worker-abandon` |\n| Accepted `worker_done` | Reuse, retain, or release |\n| Remote contact lost | Preserve `unverifiable`; do not stop or retry from absence alone |\n| `unverifiable` liveness | Keep waiting or inspect; never stop, abandon, retry, or release |\n| Proven `exited` agent | Enumerate with `worker-list`; follow its `nextAction` |\n\n## Inspect before acting\n\n```text\nORCA orchestration worker-list --run --json\nORCA orchestration worker-list --run --include-remote --json\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\n```\n\n`worker-list` is the enumerating command and the authority on agent liveness:\neach row carries `projection.liveness`, `projection.attention.categories`,\n`projection.attention.requiresAction`, and a literal `projection.nextAction`\nargv to run. Always scope it with `--run `; an unscoped list reports\nevery Dispatch this runtime has ever recorded and buries the live ones.\n`worker-show`'s `observation.status` is PTY liveness only, so a `live` terminal\nwhose agent died at a trust prompt still reads `live` there.\n\nWhen the two disagree, the fleet verdict decides — unless the fleet row is\n`unverifiable` for a reason that names a gap on this client rather than a fact\nabout the worker. `missing_status`, `host_unavailable`, and\n`capability_unsupported` are such gaps: the first means this runtime holds no\nstatus row, the second that it could not ask the execution host at all, and the\nthird that a stale peer answered but lacks the fleet-snapshot capability.\nAgainst any of them, a `worker-show` verdict sourced from the execution host is\nthe better evidence and outranks the row. Only `host_unavailable` is contact\nloss; the other two mean the host was never asked or answered without the\ncapability.\n\nThis never promotes absence. `unverifiable` from either command still authorizes\nnothing — only a positive `live` or `exited` verdict does.\n\nA worker started with `--on ` reads `unverifiable` until you\nenumerate with `--include-remote`, which asks its execution host for the\nverdict. Rows come newest first and past 100 the response pages, so follow\n`page.nextCursor` with `--cursor ` until `page.hasMore` is false.\n\n## Stall needs positive evidence\n\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Only then choose `worker-stop` or `worker-abandon`.\n\n`unverifiable` is always absence — `missing_status`, `stale_status`,\n`restored_unconfirmed`, or a remote worker with no connection — and a null\n`agentWait` or an unchanged `worker-read` tail is that same absence seen again.\nAbsence never authorizes stop, abandon, retry, or release: keep waiting, or\ninspect until you hold one of the positive signals above. A `nextAction` that\nnames an inspecting command is asking for evidence, not for cleanup.\n\n`worker-read --source auto` uses a proven provider transcript when available and\notherwise returns bounded terminal output with a typed `fallbackReason`.\nContinue with its top-level cursor, which is pinned to that source. If Orca\nreports `source_changed`, restart without the old cursor. A bounded initial\ntranscript tail can return an EOF cursor that follows only newly appended records;\nread `contentComplete`, `clipping`, and `warnings` before assuming omitted older\nrecords are pageable. Never guess a provider session ID, transcript path, or\nremote terminal handle.\n\n## Was the mutation applied?\n\nWhen a mutation's response was lost and named no Dispatch, do not replay blind.\nEvery orchestration mutation accepts `--retry-request `, which reuses one\noperation identity so Orca can replay, join, or recover it instead of starting a\nduplicate. Ask what happened first:\n\n```text\nORCA orchestration request-show --request --json\n```\n\n`completed` means the mutation already took effect; read its recorded receipt\ninstead of rerunning. `pending` means the original mutation is still running or\nOrca restarted before recording its outcome; replay the original command with\n`--retry-request `. `absent` means this runtime holds no receipt\nunder your caller identity — that is not proof nothing happened, so inspect the\naffected Task, Dispatch, and terminal before deciding whether to retry.\n\nWhen a worker's terminal accepted input but the submit is unconfirmed, use\n`terminal send --wait-submit `: it observes the accepted prompt for that\nlong and, on timeout, returns the input-accepted receipt without resending.\n\n## Refused starts\n\n`dispatch` and `worker-start` refuse the following preflight cases with a stable\n`error.code`; read it before choosing a recovery, and treat `error.data.nextSteps`\nas the exact recovery text. Older hosts may omit `data`, so treat every field as\noptional.\n\n| Code | Meaning | Recovery |\n| -------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| `task_not_found` | No Task with that id, or not in the bound Run (`data.taskId`, `data.runId`) | Check `task-list --json`; create the Task with `task-create` if it does not exist |\n| `task_not_startable` | Task cannot start now: not `ready`, or invalid `--retry-of` (`data.status`, `data.unmetDependencies`, `data.retryOf`) | Wait for running dependencies with `check --wait`; retry or unblock failed ones; inspect `dispatch-show` if already dispatched |\n| `inject_rejected` | `--inject` refused because no recognized agent runs in the target (`data.terminal`, `data.reason`) | Start a recognized agent there or pick another terminal; or dispatch without `--inject` and use `terminal send` |\n| `runtime_error` | Any other failure, including a target terminal that already owns an active Dispatch | Read the message, inspect state, and do not retry unchanged |\n\n## Retry, stop, and abandon\n\nRetry only a positively proven failed or stopped attempt. Name the failed Task\nwith `--task`, since `--spec` creates a new one. Placement is never silently\ninherited:\n\n```text\nORCA orchestration worker-start --task --retry-of --worktree --agent --json\n```\n\nAfter three consecutive failures for one Task, its dispatch context\ncircuit-breaks and the Task is failed. Do not route around that boundary with a\nnew Run or an unrelated Dispatch.\n\nFor `outcome_unknown`, inspect first, then make an explicit choice:\n\n```text\nORCA orchestration worker-stop --dispatch --json\nORCA orchestration worker-abandon --dispatch --json\n```\n\n`worker-stop` closes only the exact proven supervised agent terminal. It never\ndeletes the worktree, setup terminal, configured tabs, or unrelated processes.\n`worker-abandon` fences orchestration while accepting that resources may remain\nlive; it performs no remote, process, or filesystem action.\n\n## Retain and release\n\n```text\nORCA orchestration worker-retain --dispatch --json\nORCA orchestration worker-release --dispatch --json\n```\n\nRetain only when the user explicitly wants the settled terminal kept live.\nRelease works after succeeded and failed reports, archives readable output, and\ncloses only the exact terminal owned by that settled Dispatch. Replays may call\nrelease again safely. Reused, pre-existing, setup, coordinator, active,\nuser-taken-over, and unproven terminals are retained.\n\nA `worker-start` that failed before its agent was ready still owns the terminal\nit created. Its receipt names `worker-release`, and `worker-list` reports that\nrow as `reclaimable`; release it there rather than closing the terminal by hand.\n\nNever release because of timeout, TUI idle, heartbeat, status, question,\nescalation, or stale/rejected completion. If the receipt says `release_pending`\nor `release_unknown`, follow its exact recovery action. Never substitute\n`terminal close`.\n\n`orchestration reset` is destructive recovery. Do not run it during active\ncoordination unless the user explicitly abandons that state.\n\n\n\n# Worker contract\n\nThe injected preamble is authoritative. Copy its command rather than\nreconstructing flags. In particular, preserve the exact executable, worker\nhandle, Dispatch capability, Task ID, and Dispatch ID.\n\n## Heartbeat\n\nSend heartbeats only at the cadence required by the live preamble. Skip them\nwhile blocked inside `ask` or `check --wait`; those calls are liveness signals.\n\n```text\nORCA orchestration send --from --dispatch-capability --type heartbeat --subject \"alive\" --task-id --dispatch-id --phase \"\"\n```\n\nUse typed lifecycle flags, not a hand-written JSON payload. A heartbeat proves\nliveness, never completion.\n\n## Ask and resume\n\nUse Orca `ask` whenever the coordinator must answer. Never open a local question\nTUI the coordinator cannot answer.\n\n```text\nORCA orchestration ask --from --dispatch-capability --question \"\" --options \",\" --timeout-ms 600000\n\nORCA orchestration ask --from --dispatch-capability --resume --timeout-ms 600000\n```\n\nA timeout or disconnect leaves the original question pending. Resume its\nmessage ID; do not create a duplicate question.\n\n## Reading coordinator follow-ups\n\nThe coordinator steers a running worker with `send --to dispatch:`. That\nenqueue is durable but does not interrupt you, so nothing arrives unless you\nlook:\n\n```text\nORCA orchestration check --terminal --json\n```\n\nRun it at each natural checkpoint — before starting a new file, after a test\nrun — and once more immediately before `worker_done`, so a redirect or a\ncancellation lands before the Task settles. `check` names its caller with\n`--terminal`, never `--from`. Stop checking after `worker_done`.\n\nIf `check` returns `consumer_fenced`, this process no longer owns its Dispatch:\nthe Attempt was re-attached to another worker or settled without you. Stop, do\nnot send `worker_done`, and do not retry the check. An empty `check` never means\nyou were replaced; `consumer_fenced` is the only way you learn that.\n\n## Escalation\n\nEscalate only before completion and only when the coordinator must intervene:\n\n```text\nORCA orchestration send --from --dispatch-capability --type escalation --subject \"Blocked: \" --body \"
\" --task-id --dispatch-id \n```\n\n## Completion\n\nSend exactly one terminal report. `--body` is three sentences: what changed,\nwhat was found, and what remains. Use `--outcome failed` when the requested work\nis not complete; never hide failure in prose or silently exit.\n\nAppend `--files-modified` or `--report-path` only when applicable, using actual\npaths. Do not send documentation placeholders as metadata.\n\n```text\nORCA orchestration send --from --dispatch-capability --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded\n```\n\nAfter `worker_done`, end the dispatched turn and idle. Do not poll, close your\nown terminal, or begin unrelated work. A later direct user instruction is new\nuser-owned work and must not reuse settled lifecycle IDs; a supervised follow-up\narrives with a fresh preamble and Task block.\n" +const ORCHESTRATION_FULL_MARKDOWN = "---\nname: orchestration\ndescription: >-\n Coordinate supervised Orca workers: threaded messages, blocking ask/reply,\n task dispatch, worker_done/escalation waits, task DAGs, decision gates,\n coordinator loops, and decomposing work across agents. Use `orca-cli` for full\n ownership handoffs — \"hand off\", \"handoff\", \"handover\", \"give this to another\n agent\", \"another worktree\" — unless asked to supervise, monitor, or coordinate\n a DAG, and for terminal control, lightweight terminal prompts, shell commands,\n Orca worktree management, and reading or waiting on terminals.\n---\n\n# Orca orchestration\n\nOrchestration is Orca's structured coordination layer. It records who owns work,\nwhich attempt is authoritative, and when supervised work has settled.\n\n## Outcome\n\n**Result:** every in-scope Task has one explicit outcome and every settled worker\nterminal has a next owner or cleanup decision. **Next consumer:** the user who\nrequested supervision. **Done:** all expected Dispatches have settled, every\ndelivered message was processed before acknowledgment, each settled worker was\nreused, explicitly retained, or released, and the turn ends only when the report\nto that user names, per Task, its outcome, the evidence behind it, and any\nunresolved blocker.\n\n**Safe failure:** preserve work and authority and report the state as unknown or\n`unverifiable`. Only positive proof of exit authorizes stop, abandon, or retry,\nand only an accepted settlement authorizes release. Every other observation,\nabsence included, is a checkpoint.\n\n## Classify the role\n\n| Current context | Role | Route |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------ |\n| The user explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use a decision gate, or manage ask/reply | Coordinator | Use the supervised loop below |\n| The current prompt contains a live injected preamble with Task and Dispatch IDs | Dispatched worker | Follow the preamble and the worker obligations below |\n| The user asks to hand off ownership or start another agent/worktree without supervision | Handoff owner | Use `orca-cli`; create no Run, Task, or Dispatch and do not monitor completion |\n| A message carries a legacy authority label | Compatibility operator | Load the legacy contract reference before any lifecycle mutation |\n| No live preamble and no explicit supervision | Ordinary terminal agent | Do not emit lifecycle messages; use `orca-cli` for terminal/worktree work |\n\nModel or effort selection does not make a handoff supervised. Never substitute a\nnon-Orca subagent tool when Orca orchestration provenance was requested.\n\n## Authority and safety floor\n\n- A Run is a durable namespace and coordinator inbox; it does not schedule or\n place workers. A Task is work. A Dispatch is one authoritative Task attempt.\n- Lifecycle authority comes from the active Dispatch, not a terminal title,\n copied ID, old database row, provider transcript, or visible pane.\n- Workers use the exact executable, handle, capability, Task ID, and Dispatch ID\n in the live preamble. Never reconstruct, translate, or broaden those arguments.\n- After remote start, address the worker by Dispatch ID. The execution host owns\n process, filesystem, transcript, stop, and cleanup facts. Preserve the verdicts\n `live` / `unverifiable` / `exited`; contact loss is not process death.\n- Liveness is layered: `worker-list`'s `projection.liveness` is the fleet verdict\n for the agent; `worker-show`'s `observation.status` is PTY liveness only. A live\n terminal can still hold a dead or stuck agent.\n- Folder workspaces are valid; never require Git or assume a worktree.\n- Clients and remote servers update independently. Treat unknown optional fields\n as absent. A new stream operation requires advertised capability because old\n decoders may silently drop unknown opcodes. Never fall back to local execution\n when remote authority or capability is unproven.\n- Use the executable you used to run `skills get` for the entire run. In the\n examples below, replace `ORCA` with it; do not create a shell variable or run\n `ORCA` literally. If it fails, report that exact error instead of switching.\n- Your address is `caller.address` in `ORCA status --json`: `session:` in a\n chat, your handle in a terminal. Never name another agent with `--from`/`--terminal`.\n- A successful `orchestration send` proves durable enqueue; its wake or nudge is\n best-effort attention only and does not prove the recipient read or accepted it.\n\n## Worker obligations\n\nThe injected preamble is authoritative. A dispatched worker must:\n\n1. Do only the current Task and use the preamble's `ask` command for a blocking\n coordinator question. Never open a local question TUI the coordinator cannot\n answer. Resume the same message ID after an ask timeout.\n2. Send heartbeats only at the cadence in the preamble. A heartbeat proves\n liveness, not completion.\n3. Read coordinator follow-ups at each natural checkpoint — before starting a\n new file, after a test run — and once more immediately before `worker_done`,\n with the preamble's own `check` command.\n4. Send `worker_done` exactly once, from the dispatched terminal, with a\n three-sentence executive summary, both lifecycle IDs, and explicit\n `--outcome succeeded` or `--outcome failed`. Never encode failure only in prose.\n5. Append `--files-modified` and `--report-path` only with real values when\n applicable. After `worker_done`, end the dispatched turn and idle; do not poll\n or start new work.\n\nA direct user instruction after completion starts new user-owned work and takes\nprecedence over the idle rule. Do not reuse the settled lifecycle IDs.\n\n## Canonical supervised loop\n\nConfirm the runtime, bind one Run, and start the full independent wave before\nwaiting. `worker-start --spec` creates the Task and its attempt in one call:\n\n```text\nORCA status --json\nORCA orchestration run-create --objective \"\" --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json\nORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json\nORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nIf `worker-start` exits non-zero, do not relaunch. Read the receipt's\n`failedStage` and `residualResources`, then load\n`references/recovery-and-cleanup.md`.\n\nUse `task-create` plus `worker-start --task ` for planned fan-out with\ndependencies or a retry of a known Task. Use dependencies only for real ordering\nand prefer parallel waves over chains deeper than three or four steps; nested\nworkers obey the depth limit, and a new Run does not reset the caller's depth.\n\nA consuming `check` takes its caller from the environment in a chat or Orca\nterminal; elsewhere pass your own `--terminal `, never `--from`. It\nreturns the bound Run's oldest FIFO Delivery and replays that batch until\nacknowledged. Process every message: reply to questions, validate each\n`worker_done` against the expected active Dispatch, and decide each settled\nterminal's next owner before the ack:\n\n```text\nORCA orchestration reply --id --body \"\" --json\nORCA orchestration worker-release --dispatch --json\nORCA orchestration check --ack --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json\n```\n\nKeep waiting until every expected Dispatch settles. A timeout or empty result is\na checkpoint, not a failure. Do not stop, retry, release, or launch a duplicate\neditor without the positive proof `## Outcome` requires.\n\nAfter three consecutive empty waits, stop waiting blindly and enumerate with\n`ORCA orchestration worker-list --include-remote --json` (defaults to the bound\nRun; `--run ` overrides; the receipt's `scope` names which), acting on\neach row's `projection.attention` categories, `projection.attention.requiresAction`, and literal `projection.nextAction` argv.\nRows come newest first and page at 100: while `page.hasMore`, follow `page.nextCursor` with `--cursor `.\nA `none` `nextAction` has no argv to run: read `liveness.reason` and keep waiting\nwith `check --wait`. Absence never earns an argv; settlement and pending work still do.\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Then load `references/recovery-and-cleanup.md` and choose\n`worker-stop` or `worker-abandon` explicitly. `unverifiable` is absence,\nincluding when `worker-show` reports `agentWait` null. Absence never authorizes\nstop, abandon, retry, or release; keep waiting or inspect. A chat coordinator\nends its turn instead of `check --wait`; see `references/coordinator-loop.md`.\n\n`worker-start` is the normal path, composing placement, terminal readiness,\nprompt injection, and supervised resource ownership. `dispatch --inject` leaves\nan operator-created process unsupervised and is only for an expressiveness gap.\n\n## Task-spec contract\n\nEvery Task spec must be self-contained and name:\n\n- **Target:** the files, component, or environment in scope.\n- **Change:** the concrete result to produce.\n- **Constraints:** invariants, compatibility rules, and do-not-touch boundaries.\n- **Ownership:** what this worker may edit and any coordination boundary.\n- **Observable acceptance:** the test, output, or evidence that proves completion.\n\n## Completion accounting\n\nAfter an accepted success or failure report, immediately do exactly one:\n\n1. Reuse the same proven agent terminal for an immediate follow-up Dispatch.\n2. Record user-requested retention with `worker-retain`.\n3. Run `worker-release`.\n\nRelease is post-settlement cleanup, not cancellation. Only an accepted\nsettlement authorizes it; no other observation does. If release is uncertain,\nfollow its exact recovery receipt and never substitute `terminal close`.\n\nA valid `worker_done` settles the Task and Dispatch automatically; do not follow\nit with `task-update --status completed`. Enumerate the terminals still owing a\ndecision with `worker-list --run --terminal-state reclaimable --json`,\nand do not end the coordinator turn until it returns none.\n\n## Conditional references\n\nThis compact guide is sufficient for the normal local loop. At an action gate\nbelow, run `ORCA skills get orchestration --reference references/.md` and\nread only that document; `--references` lists the names. If the CLI rejects\n`--reference`, run `ORCA skills get orchestration --full` once instead: it\nreturns this exact kernel and every reference, so read only the named one. If an\nolder CLI rejects `--full`, keep this kernel's safety floor, use that command's\n`--help`, and never guess newer flags.\n\n| Action gate | Bundled reference |\n| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |\n| Chat coordination, expanded DAG waves, launch model/effort, same-terminal reuse, or review ownership | `references/coordinator-loop.md` |\n| You are a dispatched worker and the live preamble does not answer your question, or `check` returned an error | `references/worker-contract.md` |\n| New worktree, exact workspace, SSH, WSL, or connected-server placement | `references/placement-and-remote.md` |\n| Inbox replay, follow-up messages, group addresses, or decision gates | `references/messaging-and-gates.md` |\n| Failed/stopped/unknown attempts, retry, stop, abandon, retain, or uncertain release | `references/recovery-and-cleanup.md` |\n| Custom argv or terminal topology that `worker-start` cannot express | `references/low-level-topology.md` |\n| Any legacy label, adopted Run, compatibility receipt, or takeover | `references/legacy-contract-migration.md` |\n\nRetired scheduler commands are not aliases for Run creation. Recovery commands\nmust provide their exact next action; follow it with the same selected executable.\n\n---\n\n# Bundled references\n\nThese references belong to the version-matched guide above. Read only the documents named by its action gates.\n\n\n\n# Coordinator loop\n\nLoad this reference for coordinating from a chat session, expanded DAG waves,\nper-invocation launch preferences, same-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Coordinating from a chat session\n\nWhen `ORCA status --json` reports `caller.kind` `session`, you coordinate from a\nchat. Never block in `check --wait`: your shell tool has its own timeout, and\nOrca wakes you instead. When messages reach your Run, Orca starts a new turn in\nthis chat once you are idle, saying `You have orchestration message(s)` and\nnaming the `check` to run.\n\n1. Bind one Run and start the full independent wave.\n2. End your turn.\n3. On each such turn run the `check` it names, without `--wait`. Process every\n message as the compact guide requires, then acknowledge with\n `ORCA orchestration check --ack --json`, which also returns the\n next batch. Repeat until no Delivery is returned.\n4. End your turn again. When every expected Dispatch has settled, report.\n\nA turn with no new Delivery is a checkpoint, not a failure. The compact guide's\nempty-wait enumeration applies when a turn arrives and a Dispatch you expected\nhas still not settled. `/clear` gives the chat a new session and address; Orca\nmoves your Runs and unread mail to it.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n\n\n\n# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n\n\n\n# Low-level topology\n\nLoad this reference only when `worker-start` cannot express required custom argv\nor terminal topology. It is not the normal supervised loop and is never a full\nhandoff recipe.\n\n```text\nORCA terminal create --worktree active --title --command \"\" --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\nORCA orchestration dispatch --task --to --inject --json\n```\n\nWait for readiness only when startup could lose injected input. Prefer\nagent-first `worker-start` whenever its argv and topology are sufficient.\n\n`dispatch --inject` creates authoritative Task/Dispatch context but deliberately\nkeeps an operator-created process unsupervised: it creates no supervised worker\nresource row. `worker-show`, `worker-read`, and `worker-list` report the lane as\n`unsupervised`; `worker-stop` and `worker-abandon` do not close that process, and\nsettled retain/release take no process action.\n\nUse `worker-start --terminal ` when lifecycle ownership of an existing\nagent terminal is required. Never imply that low-level dispatch retroactively\nowns a process, never use it to route around the nested-depth limit, and never\nuse it for an ownership handoff.\n\n\n\n# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` in a chat session, whose caller is always\n`session:`, and inside an Orca terminal, where Orca resolves the caller.\nPass your own handle explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups. A chat coordinator never waits: it\nchecks without `--wait` on each turn Orca starts for new mail.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\ncapability arguments in its preamble. Any live chat session on this host is\nreachable at `session:`, its Orca session id, never the provider's id (it\nchanges on `/clear`). `ORCA status --json` reports your own as `caller.address`;\na `caller` with `live: false` carries the refusal that stops you acting as that\nsession, and `null` means the shell has no orchestration identity. A user may\ncopy a chat's address with its Copy Orchestration Address menu action. `/clear`\ngives a chat a new address: Orca moves its Runs and unread mail there, and a\nsend to the old one is refused with the new one named. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n\n\n\n# Placement and remote execution\n\nLoad this reference before creating a new worktree or placing work through SSH,\nWSL, or another connected Orca server.\n\n## Placement choices\n\nA fresh worker means a fresh agent terminal, not a new Git worktree. Use the\ncurrent or an exact existing workspace by default. Create a worktree only when\nthe user requested one or a concrete checkout or filesystem conflict makes\nsharing unsafe.\n\n```text\n# Current workspace; setup is not rerun.\nORCA orchestration worker-start --task --worktree current --agent codex --json\n\n# Stacked child worktree.\nORCA orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n\n# Independent top-level worktree.\nORCA orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nCurrent and exact existing workspaces create a fresh terminal unless\n`--terminal` is explicit. Folder workspaces are first-class; do not invoke Git\nor require worktree lineage when the selected workspace is a folder.\n\nRegister a folder workspace through project setup. `repo add --path `\nrequires a valid Git repository and rejects a plain directory:\n\n```text\nORCA project setup-existing-folder --project --host --path --kind folder --json\n```\n\nThen place work on the returned workspace with an exact selector. A worktree\nselector needs the full `::` value Orca returned, passed as\n`id:`; a bare repo id is not a worktree id. `new-child` and\n`new-top-level` are worktree creation and do not apply to a folder.\n\nNew worktrees use agent-first creation and run setup by default. Preserve the\nrepository's startup policy: `start-immediately` can report setup as `running`,\nwhile `wait-for-setup` gates prompt delivery on success. Orca lineage, Git base,\nfilesystem isolation, coordination parentage, UI grouping, and execution host\nare separate decisions.\n\n## Connected servers\n\nThe Run and Tasks remain authoritative on the current server. `--on` selects\nonly the worker's execution server and appears only on `worker-start`:\n\n```text\nORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run --json\n```\n\nRemote `current` and `new-child` are invalid because they are ambiguous across\nservers. Use an exact discovered remote workspace, or `new-top-level` with an\nexact remote repository selector. After start, route every follow-up, read,\nstop, and cleanup by Dispatch ID; never repeat `--on` or substitute a remote\nterminal handle.\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\nORCA orchestration worker-list --run --include-remote --json\n```\n\n`worker-list` reads local fleet state only; enumerate remote workers with\n`--include-remote` or every one of them reads `unverifiable`. Scope every list\nwith `--run `: unscoped, it reports every Dispatch this runtime has\nrecorded, and the workers you are waiting on are lost in that history.\n\n## Execution-host and mixed-version floor\n\nThe execution host owns process, filesystem, transcript, stop, and cleanup\nfacts. Render only `live`, `unverifiable`, or `exited`. Connection loss, relay\nabsence, missing client inventory, or timeout yields `unverifiable`, never\nsynthetic exit and never a client-local substitute action.\n\nClients and servers update independently. Optional response fields may be\nabsent. Forward model/effort, transcript reads, cleanup, or another new remote\noperation only when the peer advertises the relevant capability; unknown stream\nopcodes can be silently dropped. A narrow unsupported response may degrade to a\ndocumented older path, but must not broaden the target or cross the execution\nboundary. Changing host-published content reaches old clients even without a\nwire-shape change, so preserve established semantics or negotiate the behavior.\n\nFor WSL, use the exact executable and arguments returned by Orca so the distro\nand packaged launcher remain bound. Do not translate a printed `orca-ide`\nrecovery command into a PATH-resolved local command.\n\n\n\n# Recovery and cleanup\n\nLoad this reference only after a failed/stopped/unknown attempt, explicit retry\ndecision, stop/abandon request, retention request, or uncertain release.\n\n| Proven state | Safe action |\n| ----------------------- | ------------------------------------------------------------------ |\n| `ready` or active | Keep waiting; optionally read bounded output |\n| `failed` or `stopped` | Start a replacement with `--retry-of`; repeat placement explicitly |\n| `outcome_unknown` | Inspect, then choose `worker-stop` or explicit `worker-abandon` |\n| Accepted `worker_done` | Reuse, retain, or release |\n| Remote contact lost | Preserve `unverifiable`; do not stop or retry from absence alone |\n| `unverifiable` liveness | Keep waiting or inspect; never stop, abandon, retry, or release |\n| Proven `exited` agent | Enumerate with `worker-list`; follow its `nextAction` |\n\n## Inspect before acting\n\n```text\nORCA orchestration worker-list --run --json\nORCA orchestration worker-list --run --include-remote --json\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\n```\n\n`worker-list` is the enumerating command and the authority on agent liveness:\neach row carries `projection.liveness`, `projection.attention.categories`,\n`projection.attention.requiresAction`, and a literal `projection.nextAction`\nargv to run. Always scope it with `--run `; an unscoped list reports\nevery Dispatch this runtime has ever recorded and buries the live ones.\n`worker-show`'s `observation.status` is PTY liveness only, so a `live` terminal\nwhose agent died at a trust prompt still reads `live` there.\n\nWhen the two disagree, the fleet verdict decides — unless the fleet row is\n`unverifiable` for a reason that names a gap on this client rather than a fact\nabout the worker. `missing_status`, `host_unavailable`, and\n`capability_unsupported` are such gaps: the first means this runtime holds no\nstatus row, the second that it could not ask the execution host at all, and the\nthird that a stale peer answered but lacks the fleet-snapshot capability.\nAgainst any of them, a `worker-show` verdict sourced from the execution host is\nthe better evidence and outranks the row. Only `host_unavailable` is contact\nloss; the other two mean the host was never asked or answered without the\ncapability.\n\nThis never promotes absence. `unverifiable` from either command still authorizes\nnothing — only a positive `live` or `exited` verdict does.\n\nA worker started with `--on ` reads `unverifiable` until you\nenumerate with `--include-remote`, which asks its execution host for the\nverdict. Rows come newest first and past 100 the response pages, so follow\n`page.nextCursor` with `--cursor ` until `page.hasMore` is false.\n\n## Stall needs positive evidence\n\nLeave the wait only on positive proof the agent stopped: `exited` liveness, the\nworker's own observation of process exit, or a transcript whose final agent turn\nsent no `worker_done`. Only then choose `worker-stop` or `worker-abandon`.\n\n`unverifiable` is always absence — `missing_status`, `stale_status`,\n`restored_unconfirmed`, or a remote worker with no connection — and a null\n`agentWait` or an unchanged `worker-read` tail is that same absence seen again.\nAbsence never authorizes stop, abandon, retry, or release: keep waiting, or\ninspect until you hold one of the positive signals above. A `nextAction` that\nnames an inspecting command is asking for evidence, not for cleanup.\n\n`worker-read --source auto` uses a proven provider transcript when available and\notherwise returns bounded terminal output with a typed `fallbackReason`.\nContinue with its top-level cursor, which is pinned to that source. If Orca\nreports `source_changed`, restart without the old cursor. A bounded initial\ntranscript tail can return an EOF cursor that follows only newly appended records;\nread `contentComplete`, `clipping`, and `warnings` before assuming omitted older\nrecords are pageable. Never guess a provider session ID, transcript path, or\nremote terminal handle.\n\n## Was the mutation applied?\n\nWhen a mutation's response was lost and named no Dispatch, do not replay blind.\nEvery orchestration mutation accepts `--retry-request `, which reuses one\noperation identity so Orca can replay, join, or recover it instead of starting a\nduplicate. Ask what happened first:\n\n```text\nORCA orchestration request-show --request --json\n```\n\n`completed` means the mutation already took effect; read its recorded receipt\ninstead of rerunning. `pending` means the original mutation is still running or\nOrca restarted before recording its outcome; replay the original command with\n`--retry-request `. `absent` means this runtime holds no receipt\nunder your caller identity — that is not proof nothing happened, so inspect the\naffected Task, Dispatch, and terminal before deciding whether to retry.\n\nWhen a worker's terminal accepted input but the submit is unconfirmed, use\n`terminal send --wait-submit `: it observes the accepted prompt for that\nlong and, on timeout, returns the input-accepted receipt without resending.\n\n## Refused starts\n\n`dispatch` and `worker-start` refuse the following preflight cases with a stable\n`error.code`; read it before choosing a recovery, and treat `error.data.nextSteps`\nas the exact recovery text. Older hosts may omit `data`, so treat every field as\noptional.\n\n| Code | Meaning | Recovery |\n| -------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n| `task_not_found` | No Task with that id, or not in the bound Run (`data.taskId`, `data.runId`) | Check `task-list --json`; create the Task with `task-create` if it does not exist |\n| `task_not_startable` | Task cannot start now: not `ready`, or invalid `--retry-of` (`data.status`, `data.unmetDependencies`, `data.retryOf`) | Wait for running dependencies with `check --wait`; retry or unblock failed ones; inspect `dispatch-show` if already dispatched |\n| `inject_rejected` | `--inject` refused because no recognized agent runs in the target (`data.terminal`, `data.reason`) | Start a recognized agent there or pick another terminal; or dispatch without `--inject` and use `terminal send` |\n| `runtime_error` | Any other failure, including a target terminal that already owns an active Dispatch | Read the message, inspect state, and do not retry unchanged |\n\n## Retry, stop, and abandon\n\nRetry only a positively proven failed or stopped attempt. Name the failed Task\nwith `--task`, since `--spec` creates a new one. Placement is never silently\ninherited:\n\n```text\nORCA orchestration worker-start --task --retry-of --worktree --agent --json\n```\n\nAfter three consecutive failures for one Task, its dispatch context\ncircuit-breaks and the Task is failed. Do not route around that boundary with a\nnew Run or an unrelated Dispatch.\n\nFor `outcome_unknown`, inspect first, then make an explicit choice:\n\n```text\nORCA orchestration worker-stop --dispatch --json\nORCA orchestration worker-abandon --dispatch --json\n```\n\n`worker-stop` closes only the exact proven supervised agent terminal. It never\ndeletes the worktree, setup terminal, configured tabs, or unrelated processes.\n`worker-abandon` fences orchestration while accepting that resources may remain\nlive; it performs no remote, process, or filesystem action.\n\n## Retain and release\n\n```text\nORCA orchestration worker-retain --dispatch --json\nORCA orchestration worker-release --dispatch --json\n```\n\nRetain only when the user explicitly wants the settled terminal kept live.\nRelease works after succeeded and failed reports, archives readable output, and\ncloses only the exact terminal owned by that settled Dispatch. Replays may call\nrelease again safely. Reused, pre-existing, setup, coordinator, active,\nuser-taken-over, and unproven terminals are retained.\n\nA `worker-start` that failed before its agent was ready still owns the terminal\nit created. Its receipt names `worker-release`, and `worker-list` reports that\nrow as `reclaimable`; release it there rather than closing the terminal by hand.\n\nNever release because of timeout, TUI idle, heartbeat, status, question,\nescalation, or stale/rejected completion. If the receipt says `release_pending`\nor `release_unknown`, follow its exact recovery action. Never substitute\n`terminal close`.\n\n`orchestration reset` is destructive recovery. Do not run it during active\ncoordination unless the user explicitly abandons that state.\n\n\n\n# Worker contract\n\nThe injected preamble is authoritative. Copy its command rather than\nreconstructing flags. In particular, preserve the exact executable, worker\nhandle, Dispatch capability, Task ID, and Dispatch ID.\n\n## Heartbeat\n\nSend heartbeats only at the cadence required by the live preamble. Skip them\nwhile blocked inside `ask` or `check --wait`; those calls are liveness signals.\n\n```text\nORCA orchestration send --from --dispatch-capability --type heartbeat --subject \"alive\" --task-id --dispatch-id --phase \"\"\n```\n\nUse typed lifecycle flags, not a hand-written JSON payload. A heartbeat proves\nliveness, never completion.\n\n## Ask and resume\n\nUse Orca `ask` whenever the coordinator must answer. Never open a local question\nTUI the coordinator cannot answer.\n\n```text\nORCA orchestration ask --from --dispatch-capability --question \"\" --options \",\" --timeout-ms 600000\n\nORCA orchestration ask --from --dispatch-capability --resume --timeout-ms 600000\n```\n\nA timeout or disconnect leaves the original question pending. Resume its\nmessage ID; do not create a duplicate question.\n\n## Reading coordinator follow-ups\n\nThe coordinator steers a running worker with `send --to dispatch:`. That\nenqueue is durable but does not interrupt you, so nothing arrives unless you\nlook:\n\n```text\nORCA orchestration check --terminal --json\n```\n\nRun it at each natural checkpoint — before starting a new file, after a test\nrun — and once more immediately before `worker_done`, so a redirect or a\ncancellation lands before the Task settles. `check` names its caller with\n`--terminal`, never `--from`. Stop checking after `worker_done`.\n\nIf `check` returns `consumer_fenced`, this process no longer owns its Dispatch:\nthe Attempt was re-attached to another worker or settled without you. Stop, do\nnot send `worker_done`, and do not retry the check. An empty `check` never means\nyou were replaced; `consumer_fenced` is the only way you learn that.\n\n## Escalation\n\nEscalate only before completion and only when the coordinator must intervene:\n\n```text\nORCA orchestration send --from --dispatch-capability --type escalation --subject \"Blocked: \" --body \"
\" --task-id --dispatch-id \n```\n\n## Completion\n\nSend exactly one terminal report. `--body` is three sentences: what changed,\nwhat was found, and what remains. Use `--outcome failed` when the requested work\nis not complete; never hide failure in prose or silently exit.\n\nAppend `--files-modified` or `--report-path` only when applicable, using actual\npaths. Do not send documentation placeholders as metadata.\n\n```text\nORCA orchestration send --from --dispatch-capability --type worker_done --subject \"\" --body \"\" --task-id --dispatch-id --outcome succeeded\n```\n\nAfter `worker_done`, end the dispatched turn and idle. Do not poll, close your\nown terminal, or begin unrelated work. A later direct user instruction is new\nuser-owned work and must not reuse settled lifecycle IDs; a supervised follow-up\narrives with a fresh preamble and Task block.\n" // oxfmt-ignore -const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = "# Coordinator loop\n\nLoad this reference for expanded DAG waves, per-invocation launch preferences,\nsame-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n" +const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = "# Coordinator loop\n\nLoad this reference for coordinating from a chat session, expanded DAG waves,\nper-invocation launch preferences, same-terminal reuse, or review ownership. The compact guide remains the source\nof truth for the loop order and completion boundary.\n\n## Coordinating from a chat session\n\nWhen `ORCA status --json` reports `caller.kind` `session`, you coordinate from a\nchat. Never block in `check --wait`: your shell tool has its own timeout, and\nOrca wakes you instead. When messages reach your Run, Orca starts a new turn in\nthis chat once you are idle, saying `You have orchestration message(s)` and\nnaming the `check` to run.\n\n1. Bind one Run and start the full independent wave.\n2. End your turn.\n3. On each such turn run the `check` it names, without `--wait`. Process every\n message as the compact guide requires, then acknowledge with\n `ORCA orchestration check --ack --json`, which also returns the\n next batch. Repeat until no Delivery is returned.\n4. End your turn again. When every expected Dispatch has settled, report.\n\nA turn with no new Delivery is a checkpoint, not a failure. The compact guide's\nempty-wait enumeration applies when a turn arrives and a Dispatch you expected\nhas still not settled. `/clear` gives the chat a new session and address; Orca\nmoves your Runs and unread mail to it.\n\n## Ready waves\n\nCreate independent Tasks before the first wait. Encode only real dependencies,\nthen use the ready view as external memory:\n\n```text\nORCA orchestration task-create --spec \"\" --deps --json\nORCA orchestration task-list --ready --brief --json\n```\n\n`--brief` collapses whitespace and caps echoed specs at 160 characters;\n`spec_truncated` identifies shortened rows. Omit it when full specs are needed or\nwhen an older CLI rejects the flag. A nested worker must respect\n`nested_worker_depth_exceeded`; creating another Run does not reset depth.\n\n## Launch preferences\n\nFor a fresh Claude, Codex, Cursor, Antigravity, or Muse terminal, `--model`\naccepts an opaque provider model ID. Pass it only when the user named a model;\notherwise omit it so the worker inherits the user's configured agent default.\nAdd `--effort` only when that model supports it:\n\n```text\nORCA orchestration worker-start --task --worktree current --agent claude --model opus --effort high --json\nORCA orchestration worker-start --task --worktree current --agent muse --model muse-spark-1.3 --json\n```\n\nOther agents, including `opencode`, reject `--model`; they run the model set in\ntheir own config, so a coordinator wanting a same-model opencode worker relies\non that config.\n\n`--effort` requires `--model`; neither option combines with `--terminal`. A\nconnected worker server must advertise launch-preference support before Orca\nforwards either field. Compare `launch.requested` with `launch.effective`; never\nclaim a model or effort from requested arguments alone.\n\n## Reuse after settlement\n\nChoose the terminal's next owner before acknowledging the Delivery. When the\nsame exact agent has immediate follow-up work, recover the proven handle and\ntransfer cleanup ownership to the new Dispatch:\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-start --task --terminal --json\n```\n\nOtherwise explicitly retain or release the settled worker. Do not leave it live\nonly to inspect output; archived output remains available through `worker-read`.\n\n## Review ownership\n\nA review-only `worker_done` authorizes synthesis of findings, not coordinator\nfile edits. Dispatch or hand off fixes unless the user explicitly assigned them\nto the coordinator. If the user's plan names a next owner, post-review fixes and\nPR preparation remain with that owner; the coordinator routes and synthesizes.\n" // oxfmt-ignore const ORCHESTRATION_LEGACY_CONTRACT_MIGRATION_REFERENCE_MARKDOWN = "# Legacy contract migration\n\nLoad this reference only for an authority label, adopted Run, compatibility or\nrecovery receipt, or explicit legacy takeover. A newly created attempt always\nuses the current grammar.\n\n## Authority labels\n\n- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported\n command printed with the message, using the same selected executable and\n arguments supplied by the original prompt.\n- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded,\n at-least-once cutover replay. Process it idempotently and acknowledge only\n through the exact displayed guidance.\n- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or\n lifecycle mutation.\n- An unlabeled current message uses the current guide and grammar.\n\nAn explicitly selected current Run, attested current binding, current Dispatch,\nor federated attachment takes precedence over legacy fallback. A retained\nadoption record alone does not grant mutation authority. If liveness, principal\nownership, capability, or the exact legacy contract is unproven, degrade to\nread-only inspection and never fall back to local execution.\n\nAdoption preserves the live agent process, PTY/session, terminal handle,\ntab/pane, worktree or folder workspace, Task, and Dispatch. It never restarts or\nreplaces the worker and never revives the retired scheduler. Loss of lifecycle\nauthority does not invalidate the existing process, assignment, or filesystem\nwork. Exact recovery may restore the same PTY once in its original inactive\nbackground tab; it must not spawn, write, signal, stop, switch, focus, split, or\ninject a terminal.\n\n## Compatibility recovery\n\nWhen a compatibility response returns structured next-step arguments, execute\nthose exact arguments with the same selected CLI executable. Do not translate\nfrom memory, broaden the recipient, or retry as a current mutation unless the\nreceipt explicitly authorizes it.\n\nA pending ask, reply, final Dispatch settlement, and consuming check have\ndurable recovery identities. Heartbeat and escalation remain at-least-once\nacross a manual contract-boundary retry. If an ask may already have been\nanswered, run the exact non-consuming recovery check printed by Orca before\ncreating any new question. Never guess among identical question threads.\n\nOn packaged Windows, a legacy ask uses a two-step commit/resume protocol. The\ninitial command commits the question, prints its exact\n`ask --resume ` command, and exits with launcher status `75`. Run\nthat exact resume after the launcher or update boundary. For an attested WSL\nlaunch, preserve the printed `orca-ide` executable and distro route. Older WSL\nworkers without launch proof remain lifecycle read-only even while their\nterminal and filesystem work continue.\n\n## Read-only inspection and takeover\n\nRead-only inspection does not consume mail:\n\n```text\nORCA orchestration run-list --json\nORCA orchestration run-show --id run_legacy_local --json\nORCA orchestration run-show --id --json\nORCA orchestration task-list --run --json\nORCA orchestration inbox --full --json\nORCA orchestration check --terminal --peek --format --json\nORCA terminal read --terminal --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\n```\n\n`run_legacy_local` is an empty audit tombstone after adoption. Find the ordinary\nRun whose objective is `Recovered orchestration work from a contract update`.\n\nOnly when the original coordinator is unavailable or cannot prove retained\nauthority may a new live coordinator take over from its own terminal:\n\n```text\nORCA orchestration run-use --id --takeover-legacy --json\nORCA orchestration check --run --json\n```\n\nTakeover binds the authenticated invoking terminal; `--from` cannot nominate\nanother coordinator. It fences only the old coordinator and moves pending mail\ninto current Run delivery. It preserves live workers, Tasks, Dispatches, processes, and files.\nNever take over while the original coordinator is actively coordinating.\n\nDo not launch a replacement editor merely because Orca updated or authority is\nunclear. Keep the original worker as the only editor until a stable handoff\npoint, then use a fresh current Dispatch in a conflict-free placement.\n" @@ -81,7 +81,7 @@ const ORCHESTRATION_LEGACY_CONTRACT_MIGRATION_REFERENCE_MARKDOWN = "# Legacy con const ORCHESTRATION_LOW_LEVEL_TOPOLOGY_REFERENCE_MARKDOWN = "# Low-level topology\n\nLoad this reference only when `worker-start` cannot express required custom argv\nor terminal topology. It is not the normal supervised loop and is never a full\nhandoff recipe.\n\n```text\nORCA terminal create --worktree active --title --command \"\" --json\nORCA terminal wait --terminal --for tui-idle --timeout-ms 60000 --json\nORCA orchestration dispatch --task --to --inject --json\n```\n\nWait for readiness only when startup could lose injected input. Prefer\nagent-first `worker-start` whenever its argv and topology are sufficient.\n\n`dispatch --inject` creates authoritative Task/Dispatch context but deliberately\nkeeps an operator-created process unsupervised: it creates no supervised worker\nresource row. `worker-show`, `worker-read`, and `worker-list` report the lane as\n`unsupervised`; `worker-stop` and `worker-abandon` do not close that process, and\nsettled retain/release take no process action.\n\nUse `worker-start --terminal ` when lifecycle ownership of an existing\nagent terminal is required. Never imply that low-level dispatch retroactively\nowns a process, never use it to route around the nested-depth limit, and never\nuse it for an ownership handoff.\n" // oxfmt-ignore -const ORCHESTRATION_MESSAGING_AND_GATES_REFERENCE_MARKDOWN = "# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` inside an Orca terminal, where Orca resolves\nthe caller; pass it explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\ncapability arguments in its preamble. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n" +const ORCHESTRATION_MESSAGING_AND_GATES_REFERENCE_MARKDOWN = "# Messaging and gates\n\nLoad this reference for inbox replay, attempt-specific guidance, group\naddresses, blocking questions, or coordinator-managed DAG decisions.\n\nA successful `send` proves durable enqueue. Wake and nudge are best-effort\nattention only: neither proves the recipient read the message, began a turn, or\naccepted steering.\n\n## Coordinator delivery loop\n\n`check` names its caller with `--terminal ` and is the only verb that\nrejects `--from`. Omit `--terminal` in a chat session, whose caller is always\n`session:`, and inside an Orca terminal, where Orca resolves the caller.\nPass your own handle explicitly from anywhere else, including a dispatched\nworker reading coordinator follow-ups. A chat coordinator never waits: it\nchecks without `--wait` on each turn Orca starts for new mail.\n\nA consuming coordinator `check` returns the bound Run's oldest FIFO Delivery,\nup to 50 messages, and replays that exact batch until acknowledged. Process\nevery row and required terminal ownership decision before `--ack`. Type filters\ndecide when a waiter wakes; they do not authorize skipping older actionable\nmail. A Delivery therefore always carries the whole FIFO batch whatever its\ntypes, and a `check` without `--wait` hands that batch over unfiltered.\n`--peek` and `--all` are read-only inspection, not progress through the\ncoordinator inbox.\n\nAn empty wait or timeout is a checkpoint. Continue rolling waits until every\nexpected Dispatch settles. Heartbeat or visible activity means alive, not done.\n\n## Addresses\n\nUse a stable Dispatch address for attempt-specific coordinator guidance:\n\n```text\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\n```\n\nDo not substitute a remote terminal handle. Omit `--from` for ordinary\ncoordinator calls; a dispatched worker instead copies the exact `--from` and\ncapability arguments in its preamble. Any live chat session on this host is\nreachable at `session:`, its Orca session id, never the provider's id (it\nchanges on `/clear`). `ORCA status --json` reports your own as `caller.address`;\na `caller` with `live: false` carries the refusal that stops you acting as that\nsession, and `null` means the shell has no orchestration identity. A user may\ncopy a chat's address with its Copy Orchestration Address menu action. `/clear`\ngives a chat a new address: Orca moves its Runs and unread mail there, and a\nsend to the old one is refused with the new one named. `check` is the exception: it identifies\nits caller with `--terminal`, never `--from`.\n\nGroup addresses include `@all`, `@idle`, `@claude`, `@codex`, `@opencode`,\n`@gemini`, `@droid`, `@grok`, `@cursor`, and `@worktree:`. Every group but\n`@worktree:` means the live Dispatches of the sender's own Run. Mail goes\nto each `dispatch:` mailbox, except a worker coordinating a child Run\nreceives it in that `run:` mailbox. A sender bound to no Run is refused;\n`--run` must match the group audience and never grants membership.\nA Run group excludes its owning coordinator; a worker raising a blocker sends\nto `run:`. A worker that created its own Run addresses that Run's workers,\nnot its siblings. `@worktree:` reaches matching workspace terminals,\nincluding coordinators. Use groups only for intentional fan-out status or\nquestions. `worker_done`, heartbeat, and other\nDispatch lifecycle messages never target groups.\n\n## Questions and gates\n\nA worker uses `ask`; its timeout leaves one durable question pending, which the\nworker resumes by message ID. The coordinator answers that message with `reply`.\n\nUse a gate only for a coordinator-owned Task-DAG decision:\n\n```text\nORCA orchestration gate-create --task --question \"\" --options --json\nORCA orchestration gate-resolve --id --resolution \"\" --json\nORCA orchestration gate-list --task --json\n```\n\nPass `json_array` using the quoting rules of the active shell; do not copy POSIX\nsingle-quote syntax into PowerShell or `cmd.exe`.\n\nDo not create a gate merely to answer a worker's `ask`.\n" // oxfmt-ignore const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = "# Placement and remote execution\n\nLoad this reference before creating a new worktree or placing work through SSH,\nWSL, or another connected Orca server.\n\n## Placement choices\n\nA fresh worker means a fresh agent terminal, not a new Git worktree. Use the\ncurrent or an exact existing workspace by default. Create a worktree only when\nthe user requested one or a concrete checkout or filesystem conflict makes\nsharing unsafe.\n\n```text\n# Current workspace; setup is not rerun.\nORCA orchestration worker-start --task --worktree current --agent codex --json\n\n# Stacked child worktree.\nORCA orchestration worker-start --task --worktree new-child --name --agent codex --setup run --json\n\n# Independent top-level worktree.\nORCA orchestration worker-start --task --worktree new-top-level --name --agent codex --setup run --json\n```\n\nCurrent and exact existing workspaces create a fresh terminal unless\n`--terminal` is explicit. Folder workspaces are first-class; do not invoke Git\nor require worktree lineage when the selected workspace is a folder.\n\nRegister a folder workspace through project setup. `repo add --path `\nrequires a valid Git repository and rejects a plain directory:\n\n```text\nORCA project setup-existing-folder --project --host --path --kind folder --json\n```\n\nThen place work on the returned workspace with an exact selector. A worktree\nselector needs the full `::` value Orca returned, passed as\n`id:`; a bare repo id is not a worktree id. `new-child` and\n`new-top-level` are worktree creation and do not apply to a folder.\n\nNew worktrees use agent-first creation and run setup by default. Preserve the\nrepository's startup policy: `start-immediately` can report setup as `running`,\nwhile `wait-for-setup` gates prompt delivery on success. Orca lineage, Git base,\nfilesystem isolation, coordination parentage, UI grouping, and execution host\nare separate decisions.\n\n## Connected servers\n\nThe Run and Tasks remain authoritative on the current server. `--on` selects\nonly the worker's execution server and appears only on `worker-start`:\n\n```text\nORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run --json\n```\n\nRemote `current` and `new-child` are invalid because they are ambiguous across\nservers. Use an exact discovered remote workspace, or `new-top-level` with an\nexact remote repository selector. After start, route every follow-up, read,\nstop, and cleanup by Dispatch ID; never repeat `--on` or substitute a remote\nterminal handle.\n\n```text\nORCA orchestration worker-show --dispatch --json\nORCA orchestration worker-read --dispatch --limit 50 --json\nORCA orchestration send --to dispatch: --subject \"Follow-up\" --body \"\" --json\nORCA orchestration worker-list --run --include-remote --json\n```\n\n`worker-list` reads local fleet state only; enumerate remote workers with\n`--include-remote` or every one of them reads `unverifiable`. Scope every list\nwith `--run `: unscoped, it reports every Dispatch this runtime has\nrecorded, and the workers you are waiting on are lost in that history.\n\n## Execution-host and mixed-version floor\n\nThe execution host owns process, filesystem, transcript, stop, and cleanup\nfacts. Render only `live`, `unverifiable`, or `exited`. Connection loss, relay\nabsence, missing client inventory, or timeout yields `unverifiable`, never\nsynthetic exit and never a client-local substitute action.\n\nClients and servers update independently. Optional response fields may be\nabsent. Forward model/effort, transcript reads, cleanup, or another new remote\noperation only when the peer advertises the relevant capability; unknown stream\nopcodes can be silently dropped. A narrow unsupported response may degrade to a\ndocumented older path, but must not broaden the target or cross the execution\nboundary. Changing host-published content reaches old clients even without a\nwire-shape change, so preserve established semantics or negotiate the behavior.\n\nFor WSL, use the exact executable and arguments returned by Orca so the distro\nand packaged launcher remain bound. Do not translate a printed `orca-ide`\nrecovery command into a PATH-resolved local command.\n" diff --git a/src/cli/format.ts b/src/cli/format.ts index 3893eaea7e5..41d10b5b6c5 100644 --- a/src/cli/format.ts +++ b/src/cli/format.ts @@ -1,3 +1,4 @@ +import type { CliStatusCaller } from '../shared/orchestration-caller-status' import type { CliStatusResult } from '../shared/runtime-types' import { prepareComputerCliJsonResult } from './computer-format' import type { RuntimeRpcSuccess } from './runtime-client' @@ -136,10 +137,21 @@ export function formatCliStatus(status: CliStatusResult): string { `runtimeReachable: ${status.runtime.reachable}`, `runtimeConnectionState: ${status.runtime.connectionState ?? 'unknown'}`, `runtimeId: ${status.runtime.runtimeId ?? 'none'}`, - `graphState: ${status.graph.state}` + `graphState: ${status.graph.state}`, + ...(status.caller === undefined ? [] : [`caller: ${formatStatusCaller(status.caller)}`]) ].join('\n') } +function formatStatusCaller(caller: CliStatusCaller): string { + if (caller === null) { + return 'none' + } + if ('refusal' in caller) { + return `session:${caller.sessionId} (refused: ${caller.refusal.code})` + } + return `${caller.address}${caller.live ? '' : ' (not live)'}` +} + export function formatStatus(status: CliStatusResult): string { return formatCliStatus(status) } diff --git a/src/cli/handlers/core.ts b/src/cli/handlers/core.ts index 6a1b7ab3918..49450d7c19b 100644 --- a/src/cli/handlers/core.ts +++ b/src/cli/handlers/core.ts @@ -3,6 +3,7 @@ import type { CommandHandler } from '../dispatch' import { formatCliStatus, formatStatus, printResult } from '../format' import { RuntimeClientError, serveOrcaApp } from '../runtime-client' import { stripElectronRunAsNode } from '../runtime/launch' +import { resolveCliStatusCaller } from '../runtime/status-caller' import { getServeOptionValidationError } from '../../shared/serve-option-validation' function envRecord(): Record { @@ -129,6 +130,13 @@ export const CORE_HANDLERS: Record = { if (!json && !result.result.runtime.reachable) { process.exitCode = 1 } - printResult(result, json, formatStatus) + const caller = result.result.runtime.reachable + ? await resolveCliStatusCaller(client) + : undefined + printResult( + caller === undefined ? result : { ...result, result: { ...result.result, caller } }, + json, + formatStatus + ) } } diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 2d4561f3098..8f58b54f1e7 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -95,8 +95,8 @@ export const ROOT_HELP_TEXT_PRIMARY = [ '', 'Orchestration:', ' orchestration run-create Create and bind a lightweight orchestration Run', - ' orchestration run-use Bind this coordinator terminal to an existing Run', - " orchestration run-current Show this terminal's bound Run", + ' orchestration run-use Bind this coordinator to an existing Run', + " orchestration run-current Show this coordinator's bound Run", ' orchestration run-list List lightweight orchestration Runs', ' orchestration run-show Show one lightweight orchestration Run', ' orchestration send Send an inter-agent message', diff --git a/src/cli/root-help-text-secondary.ts b/src/cli/root-help-text-secondary.ts index 8602e35c49e..1ffa40eb1bd 100644 --- a/src/cli/root-help-text-secondary.ts +++ b/src/cli/root-help-text-secondary.ts @@ -112,6 +112,10 @@ export const ROOT_HELP_TEXT_SECONDARY = [ ' Most commands require a running Orca runtime. If Orca is not open yet, run `orca open` first.', ' Remote runtime access can also be supplied with ORCA_PAIRING_CODE or ORCA_ENVIRONMENT.', ' Use selectors for discovery and handles for repeated live terminal operations.', + ' Inside an Orca agent, `orca status --json` reports its orchestration address as caller.address:', + ' session: for a chat session, its terminal handle for a terminal agent.', + ' When ORCA_CLI_COMMAND is set, run that executable: "$ORCA_CLI_COMMAND" in a POSIX shell,', + ' & $env:ORCA_CLI_COMMAND in PowerShell. Bare `orca` in a login shell can reach another Orca.', '', 'Agent Sessions And Worktrees:', ' `worktree create --agent` creates a new checkout with an agent.', diff --git a/src/cli/runtime/status-caller.test.ts b/src/cli/runtime/status-caller.test.ts new file mode 100644 index 00000000000..75924e303a6 --- /dev/null +++ b/src/cli/runtime/status-caller.test.ts @@ -0,0 +1,178 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { createServer, type Server, type Socket } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap' +import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope' +import { CORE_HANDLERS } from '../handlers/core' +import { RuntimeClient } from './client' + +const SESSION = '4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' +const RUNTIME_ID = 'runtime-caller' +const IDENTITY_ENV = ['ORCA_AGENT_SESSION_ID', 'ORCA_TERMINAL_HANDLE', 'ORCA_PANE_KEY'] as const + +type ReceivedRequest = RuntimeOrchestrationEnvelope & { + id: string + method: string + params?: unknown +} + +type HostReply = { result: unknown } | { error: { code: string; message: string } } + +/** + * The real `orca status` handler and CLI client over a real Unix socket. The host's side of + * `orchestration.callerShow` is covered against the real dispatcher in orchestration-caller-show. + */ +describe.skipIf(process.platform === 'win32')('orca status reports its caller address', () => { + let server: Server + const sockets = new Set() + const received: ReceivedRequest[] = [] + const savedEnv = new Map() + let userDataPath: string + let callerShowReply: HostReply + + beforeEach(async () => { + for (const key of IDENTITY_ENV) { + savedEnv.set(key, process.env[key]) + delete process.env[key] + } + received.length = 0 + userDataPath = mkdtempSync(join(tmpdir(), 'orca-status-caller-')) + const endpoint = join(userDataPath, 'runtime.sock') + server = createServer((socket) => { + sockets.add(socket) + socket.once('close', () => sockets.delete(socket)) + socket.once('data', (data) => answer(socket, String(data).trim())) + }) + await new Promise((resolve) => server.listen(endpoint, resolve)) + writeFileSync( + getRuntimeMetadataPath(userDataPath), + JSON.stringify({ + runtimeId: RUNTIME_ID, + pid: process.pid, + transport: { kind: 'unix', endpoint }, + authToken: 'token', + startedAt: Date.now() + }) + ) + }) + + afterEach(async () => { + for (const socket of sockets) { + socket.destroy() + } + await new Promise((resolve) => server.close(() => resolve())) + vi.restoreAllMocks() + for (const [key, value] of savedEnv) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } + } + }) + + function answer(socket: Socket, line: string): void { + const request: ReceivedRequest = JSON.parse(line) + received.push(request) + const reply: HostReply = + request.method === 'status.get' + ? { + result: { + runtimeId: RUNTIME_ID, + rendererGraphEpoch: 1, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0 + } + } + : callerShowReply + const ok = 'result' in reply + socket.write( + `${JSON.stringify({ id: request.id, ok, ...reply, _meta: { runtimeId: RUNTIME_ID } })}\n` + ) + } + + async function status(json: boolean): Promise { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + await CORE_HANDLERS.status({ + client: new RuntimeClient(userDataPath), + flags: new Map(), + cwd: userDataPath, + json + }) + return String(log.mock.calls.at(-1)?.[0]) + } + + async function statusCaller(): Promise { + const printed: { result: Record } = JSON.parse(await status(true)) + return printed.result.caller + } + + function callerShowRequests(): ReceivedRequest[] { + return received.filter((request) => request.method === 'orchestration.callerShow') + } + + it('asks the host as the session its environment names, and prints what the host resolved', async () => { + process.env.ORCA_AGENT_SESSION_ID = SESSION + process.env.ORCA_TERMINAL_HANDLE = 'term_tui' + const address = { + kind: 'session', + address: `session:${SESSION}`, + sessionId: SESSION, + live: true + } + callerShowReply = { result: { caller: address } } + + expect(await statusCaller()).toEqual(address) + const [request] = callerShowRequests() + // Nothing names the caller in params: the host reads the envelope, as every verb's entry does. + expect(request?.params).toBeUndefined() + expect(request?.orchestrationCompatibilityEvidence).toMatchObject({ + agentSessionId: SESSION, + terminalHandle: 'term_tui' + }) + expect(await status(false)).toContain(`caller: session:${SESSION}`) + }) + + it('asks the host about the terminal handle a PTY agent carries', async () => { + process.env.ORCA_TERMINAL_HANDLE = 'term_mine' + callerShowReply = { + result: { caller: { kind: 'terminal', address: 'term_mine', live: false } } + } + + expect(await statusCaller()).toEqual({ kind: 'terminal', address: 'term_mine', live: false }) + expect(callerShowRequests()[0]?.orchestrationCompatibilityEvidence).toEqual({ + terminalHandle: 'term_mine' + }) + expect(await status(false)).toContain('caller: term_mine (not live)') + }) + + it("reports the host's refusal of the session instead of an address", async () => { + process.env.ORCA_AGENT_SESSION_ID = SESSION + callerShowReply = { + error: { code: 'session_caller_not_live', message: `Agent session ${SESSION} has ended.` } + } + + expect(await statusCaller()).toEqual({ + kind: 'session', + sessionId: SESSION, + live: false, + refusal: { code: 'session_caller_not_live', message: `Agent session ${SESSION} has ended.` } + }) + }) + + it('leaves the caller out when the host predates the method', async () => { + process.env.ORCA_AGENT_SESSION_ID = SESSION + callerShowReply = { error: { code: 'method_not_found', message: 'Unknown method' } } + + expect(JSON.parse(await status(true)).result).not.toHaveProperty('caller') + }) + + it('reports no caller, without asking the host, for a process with no identity', async () => { + expect(await statusCaller()).toBeNull() + expect(received.map((request) => request.method)).toEqual(['status.get']) + expect(await status(false)).toContain('caller: none') + }) +}) diff --git a/src/cli/runtime/status-caller.ts b/src/cli/runtime/status-caller.ts new file mode 100644 index 00000000000..f77e09495e9 --- /dev/null +++ b/src/cli/runtime/status-caller.ts @@ -0,0 +1,46 @@ +import { readInjectedAgentSessionId } from '../../shared/agent-session-caller-env' +import type { + CliStatusCaller, + OrchestrationCallerShowResult +} from '../../shared/orchestration-caller-status' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../shared/orchestration-session-caller-codes' +import type { RuntimeClient } from './client' +import { RuntimeClientError } from './types' + +const SESSION_REFUSAL_CODES = new Set( + Object.values(ORCHESTRATION_SESSION_CALLER_ERROR_CODES) +) + +// Resolving a session may bring up the agent-session host, which the 1s status probe cannot cover. +const CALLER_SHOW_TIMEOUT_MS = 10_000 + +/** + * This process's orchestration address, resolved by the host from the identity the orchestration + * envelope carries. `undefined` when nothing could be resolved: an older host, or a failed call. + */ +export async function resolveCliStatusCaller( + client: Pick +): Promise { + const sessionId = readInjectedAgentSessionId() + if (!sessionId && !process.env.ORCA_TERMINAL_HANDLE?.trim()) { + return null + } + try { + const response = await client.call( + 'orchestration.callerShow', + undefined, + { timeoutMs: CALLER_SHOW_TIMEOUT_MS } + ) + return response.result.caller + } catch (error) { + if (sessionId && error instanceof RuntimeClientError && SESSION_REFUSAL_CODES.has(error.code)) { + return { + kind: 'session', + sessionId, + live: false, + refusal: { code: error.code, message: error.message } + } + } + return undefined + } +} diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index 98301b36e53..71bffaf3733 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -19,6 +19,9 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ summary: 'Show app/runtime/graph readiness', usage: 'orca status [--json]', allowedFlags: [...GLOBAL_FLAGS], + notes: [ + "caller is this agent's orchestration address as Orca resolved it from its environment: session: for a chat session, the terminal handle for a terminal agent, null outside an Orca agent." + ], examples: ['orca status', 'orca status --json'] }, { diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 458afa2e525..50b1e7c765d 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -16,7 +16,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['orchestration', 'run-use'], - summary: 'Bind this coordinator terminal to an existing Run', + summary: 'Bind this coordinator to an existing Run', usage: 'orca orchestration run-use --id [--from ] [--takeover-legacy] [--retry-request ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'id', 'from', 'takeover-legacy', 'retry-request'], @@ -26,7 +26,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['orchestration', 'run-current'], - summary: 'Show the Run bound to this coordinator terminal', + summary: 'Show the Run bound to this coordinator', usage: 'orca orchestration run-current [--from ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'from'] }, @@ -83,7 +83,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ }, { path: ['orchestration', 'check'], - summary: 'Check messages for a terminal', + summary: "Check this agent's messages", usage: 'orca orchestration check [--terminal ] [--run ] [--ack ] [--unread | --peek | --all] [--types ] [--format] [--wait] [--timeout-ms ] [--retry-request ] [--json]\n' + " default: return the bound Run's oldest unacknowledged FIFO batch.\n" + @@ -110,6 +110,8 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'retry-request' ], notes: [ + 'The caller is this agent: session: in a chat session, else the Orca terminal it runs in. Omit --terminal in both; pass only your own handle elsewhere.', + 'A chat coordinator never uses --wait: Orca starts a turn in the chat when mail arrives, and that turn runs check.', 'On Windows PowerShell, quote comma-separated type filters, e.g. --types "worker_done,escalation".', '--types is the wake condition for --wait; a returned Delivery is always the whole FIFO batch, so it is never filtered by type. Without --wait it has no effect on consuming checks. Only --peek and --all filter their rows.', '--format renders the returned rows as local text only; it never writes to another terminal.', diff --git a/src/main/runtime/orchestration/__snapshots__/preamble.test.ts.snap b/src/main/runtime/orchestration/__snapshots__/preamble.test.ts.snap index dabbaf462ec..5313f6a5978 100644 --- a/src/main/runtime/orchestration/__snapshots__/preamble.test.ts.snap +++ b/src/main/runtime/orchestration/__snapshots__/preamble.test.ts.snap @@ -2,8 +2,9 @@ exports[`buildDispatchPreamble > renders a stable snapshot of the full preamble 1`] = ` "You are working inside Orca, a multi-agent IDE. You are a dispatched worker. -Your coordinator's terminal handle is: term_COORD +Your coordinator's address is: term_COORD Your task ID is: task_SNAP +Your orchestration address is: term_WORKER The coordinator cannot see this terminal, so reach it with the \`orca orchestration\` commands below; a question or result left only in this terminal never gets to it. diff --git a/src/main/runtime/orchestration/preamble.test.ts b/src/main/runtime/orchestration/preamble.test.ts index 03d9e4fc912..0734370f744 100644 --- a/src/main/runtime/orchestration/preamble.test.ts +++ b/src/main/runtime/orchestration/preamble.test.ts @@ -403,3 +403,54 @@ describe('sub-dispatch section', () => { expect(preamble.indexOf('=== SUB-DISPATCH ===')).toBeLessThan(preamble.indexOf('=== TASK ===')) }) }) + +describe('the worker is told its own orchestration address', () => { + const sessionId = '4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' + const posixSession = { sessionId, cliInvocation: '"$ORCA_CLI_COMMAND"' } as const + + it('names a terminal worker by its handle', () => { + const preamble = buildDispatchPreamble(baseParams()) + + expect(preamble).toContain('Your orchestration address is: term_worker\n') + expect(preamble).not.toContain('session:') + }) + + it('names a structured worker session: and says how its coordinator reaches it', () => { + const preamble = buildDispatchPreamble( + baseParams({ workerHandle: 'structworker_1', structuredSession: posixSession }) + ) + + expect(preamble).toContain(`Your orchestration address is: session:${sessionId}\n`) + expect(preamble).toContain('Your coordinator reaches you there or at dispatch:ctx_def456.') + expect(preamble).toContain("Your coordinator's address is: term_coord\n") + }) + + it.each([ + ['a POSIX shell', '"$ORCA_CLI_COMMAND"'], + ['PowerShell', '& $env:ORCA_CLI_COMMAND'] + ] as const)( + "runs a structured worker's commands through ORCA_CLI_COMMAND in %s, even in dev", + (_shell, cliInvocation) => { + const preamble = buildDispatchPreamble( + baseParams({ + workerHandle: 'structworker_1', + structuredSession: { sessionId, cliInvocation }, + devMode: true, + cliCommand: 'orca' + }) + ) + const commands = cliFence(preamble) + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith('#')) + + expect(commands.length).toBeGreaterThan(0) + for (const command of commands) { + expect(command.startsWith(`${cliInvocation} orchestration `)).toBe(true) + } + expect(preamble).not.toContain('orca-dev') + expect(preamble).toContain(`\`${cliInvocation}\` runs this Orca's CLI`) + expect(afterWorkerDoneSection(preamble)).toContain(`${cliInvocation} orchestration check`) + } + ) +}) diff --git a/src/main/runtime/orchestration/preamble.ts b/src/main/runtime/orchestration/preamble.ts index 208868ce45b..a606649f33c 100644 --- a/src/main/runtime/orchestration/preamble.ts +++ b/src/main/runtime/orchestration/preamble.ts @@ -1,4 +1,4 @@ -import type { OrchestrationCliCommand } from './cli-command' +import type { OrchestrationCliCommand, StructuredSessionCliInvocation } from './cli-command' import type { RuntimeAgentPromptWriteOptions } from '../runtime-terminal-contracts' import { ORCA_DISPATCH_PROMPT_LEAD_LINE } from '../../../shared/orca-dispatch-status-prompt' @@ -12,8 +12,14 @@ export type PreambleParams = { dispatchId: string dispatchCapability?: string taskSpec: string + /** The coordinator's orchestration address: a terminal handle, or `session:` for a chat. */ coordinatorHandle: string workerHandle: string + /** + * Set when the worker is a structured session. Its address is then `session:`, and it runs + * the CLI through `ORCA_CLI_COMMAND`, which names this app's CLI by absolute path. + */ + structuredSession?: { sessionId: string; cliInvocation: StructuredSessionCliInvocation } devMode?: boolean // Why: packaged WSL panes install the scoped launcher as `orca-ide`; // other execution hosts keep their existing bare `orca` bridge. @@ -52,7 +58,11 @@ export function buildDispatchPreamble(params: PreambleParams): string { // Why: in dev mode, agents must use orca-dev to connect to the dev runtime's // socket. Without this, agents inside the dev Electron app would call the // production CLI and talk to the wrong Orca instance (Section 6.4). - const cli = params.devMode ? 'orca-dev' : (params.cliCommand ?? 'orca') + const cli = params.structuredSession + ? params.structuredSession.cliInvocation + : params.devMode + ? 'orca-dev' + : (params.cliCommand ?? 'orca') const postDoneInstructions = buildPostWorkerDoneInstructions({ cli, workerKind: params.workerKind ?? 'prompt-returning-agent' @@ -66,9 +76,9 @@ export function buildDispatchPreamble(params: PreambleParams): string { // Why plain-reason wording: Claude Code tells the model pasted text may carry instructions // the user did not write, and shouted rules read as prompt injection (STA-8200). const header = `You are working inside Orca, a multi-agent IDE. You are a dispatched worker. -Your coordinator's terminal handle is: ${params.coordinatorHandle} +Your coordinator's address is: ${params.coordinatorHandle} Your task ID is: ${params.taskId} - +${buildWorkerAddressSection(params)} The coordinator cannot see this terminal, so reach it with the \`${cli} orchestration\` commands below; a question or result left only in this terminal never gets to it. Don't post to Slack, GitHub, or other channels during the run; report through these commands. @@ -160,6 +170,21 @@ export function dispatchPreambleSendOptions(requestId: string): DispatchPreamble } } +// Why: a structured worker is a chat, reached at `session:` and woken by Orca rather than a PTY. +function buildWorkerAddressSection(params: PreambleParams): string { + const session = params.structuredSession + if (!session) { + return `Your orchestration address is: ${params.workerHandle} +` + } + return `Your orchestration address is: session:${session.sessionId} +Your coordinator reaches you there or at dispatch:${params.dispatchId}. Mail that arrives while +you are idle starts a new turn in this chat; mid-task, read it with the check command below. +Run every command below exactly as written: \`${session.cliInvocation}\` runs this Orca's CLI +from ORCA_CLI_COMMAND, and a bare \`orca\` in a login shell can reach a different Orca. +` +} + function buildPostWorkerDoneInstructions({ cli, workerKind diff --git a/src/main/runtime/rpc/methods/orchestration-worker-mode-opacity.test.ts b/src/main/runtime/rpc/methods/orchestration-worker-mode-opacity.test.ts index aa8c7c58574..cb79ba36ccb 100644 --- a/src/main/runtime/rpc/methods/orchestration-worker-mode-opacity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration-worker-mode-opacity.test.ts @@ -34,7 +34,10 @@ vi.mock('./orchestration/worker/worker-topology', async (importOriginal) => ({ ...(await importOriginal>()), createStructuredWorkerSessionForWorktree: async (args: { effects: unknown[] }) => { args.effects.push({ kind: 'terminal', role: 'agent', action: 'created' }) - return { identity: { handle: STRUCTURED_HANDLE, sessionId: 'sess_worker' }, host: {} } + return { + identity: { handle: STRUCTURED_HANDLE, sessionId: 'sess_worker', agent: 'claude' }, + host: {} + } }, createExistingWorktreeWorkerTerminal: async () => ({ handle: TERMINAL_HANDLE }) })) @@ -90,6 +93,17 @@ function installStructuredCoordinator(handle: string, sessionId: string): string } /** Strips the ids that legitimately differ per dispatch, leaving what the agent is taught. */ +/** + * The two facts that legitimately differ by mode, and nothing else: the worker's own address (its + * handle, or `session:` with how mail reaches a chat) and how its shell invokes the CLI. + */ +function normalizeWorkerIdentity(preamble: string, cli: string): string { + return preamble + .replace(/^Your orchestration address is: [^\n]*\n(?:[^\n]+\n)*/m, '\n') + .split(`${cli} orchestration`) + .join(' orchestration') +} + function normalizePreamble(preamble: string, handle: string, dispatchId: string): string { return preamble .split(handle) @@ -203,9 +217,19 @@ describe('a worker cannot tell which mode it is running in', () => { expect(terminal.mode.mode).toBe('terminal') const structuredPreamble = structuredPreambles[0] as string const terminalPreamble = vi.mocked(runtime.sendTerminalAgentPrompt).mock.calls[0]?.[1] as string - expect(normalizePreamble(structuredPreamble, STRUCTURED_HANDLE, structured.dispatchId)).toBe( - normalizePreamble(terminalPreamble, TERMINAL_HANDLE, terminal.dispatchId) + expect( + normalizeWorkerIdentity( + normalizePreamble(structuredPreamble, STRUCTURED_HANDLE, structured.dispatchId), + '"$ORCA_CLI_COMMAND"' + ) + ).toBe( + normalizeWorkerIdentity( + normalizePreamble(terminalPreamble, TERMINAL_HANDLE, terminal.dispatchId), + 'orca' + ) ) + expect(structuredPreamble).toContain('Your orchestration address is: session:sess_worker\n') + expect(terminalPreamble).toContain(`Your orchestration address is: ${TERMINAL_HANDLE}\n`) // The section the structured lane used to withhold, asserted by name so the equality above // cannot pass by both preambles losing it. expect(structuredPreamble).toContain('=== SUB-DISPATCH ===') diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index ab80b91e830..ce98a055326 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -9,6 +9,7 @@ import { ORCHESTRATION_DISPATCH_METHODS } from './orchestration/runs/dispatch-me import { ORCHESTRATION_ASK_METHODS } from './orchestration/messaging/ask-methods' import { ORCHESTRATION_GATE_METHODS } from './orchestration/gates/gates' import { ORCHESTRATION_RESET_METHODS } from './orchestration/runs/reset-methods' +import { ORCHESTRATION_CALLER_METHODS } from './orchestration/caller-show' export const ORCHESTRATION_METHODS = [ ...ORCHESTRATION_RUN_METHODS, @@ -21,5 +22,6 @@ export const ORCHESTRATION_METHODS = [ ...ORCHESTRATION_DISPATCH_METHODS, ...ORCHESTRATION_ASK_METHODS, ...ORCHESTRATION_GATE_METHODS, - ...ORCHESTRATION_RESET_METHODS + ...ORCHESTRATION_RESET_METHODS, + ...ORCHESTRATION_CALLER_METHODS ] diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts new file mode 100644 index 00000000000..b2d38538ec1 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -0,0 +1,33 @@ +import type { OrchestrationCallerShowResult } from '../../../../../shared/orchestration-caller-status' +import { defineMethod } from '../../core' + +export const ORCHESTRATION_CALLER_METHODS = [ + defineMethod({ + name: 'orchestration.callerShow', + params: null, + // Why no params: the answer comes from the identity the caller's environment carries, which the + // dispatch entry already resolved (a session) or the envelope evidence names (a terminal). + // A session the entry cannot admit never reaches here: its refusal is the answer. + handler: ( + _params, + { runtime, orchestrationCaller, orchestrationCompatibilityEvidence } + ): OrchestrationCallerShowResult => { + if (orchestrationCaller) { + return { + caller: { + kind: 'session', + address: orchestrationCaller.actor, + sessionId: orchestrationCaller.sessionId, + live: true + } + } + } + const handle = orchestrationCompatibilityEvidence?.terminalHandle + if (!handle) { + return { caller: null } + } + const identity = runtime.resolveTerminalIdentity(handle) + return { caller: { kind: 'terminal', address: identity.handle, live: identity.live } } + } + }) +] diff --git a/src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts b/src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts index a037a1d473d..f729db58b93 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/runs.test.ts @@ -26,7 +26,8 @@ describe('orchestration RPC methods', () => { it('registers all expected methods', () => { const registry = buildRegistry(ORCHESTRATION_METHODS) - expect(registry.size).toBe(41) + expect(registry.size).toBe(42) + expect(registry.has('orchestration.callerShow')).toBe(true) expect(registry.has('orchestration.workerRelease')).toBe(true) expect(registry.has('orchestration.workerRetain')).toBe(true) expect(registry.has('orchestration.workerList')).toBe(true) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.test.ts new file mode 100644 index 00000000000..f8d4c33da6e --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.test.ts @@ -0,0 +1,107 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { deliverWorkerDispatchPreamble } from './deliver-worker-dispatch-preamble' + +const sent = vi.hoisted((): { preambles: string[] } => ({ preambles: [] })) +vi.mock('../../orchestration-structured-worker-session', () => ({ + sendStructuredWorkerPreamble: async (args: { preamble: string }) => { + sent.preambles.push(args.preamble) + } +})) + +const SESSION = '4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' + +function runtime(prompts: string[]): OrcaRuntimeService { + const fake: Pick< + OrcaRuntimeService, + 'getNestedWorkerMaxDepth' | 'getTerminalOrchestrationCliCommand' | 'sendTerminalAgentPrompt' + > = { + getNestedWorkerMaxDepth: () => 0, + getTerminalOrchestrationCliCommand: () => 'orca', + sendTerminalAgentPrompt: async (handle, text) => { + prompts.push(text) + return { handle, accepted: true, bytesWritten: text.length } + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliverWorkerDispatchPreamble reads only the three members the fake implements. + return fake as OrcaRuntimeService +} + +type StructuredSession = Parameters[0]['structuredSession'] + +function structuredSession(agent: 'claude' | 'codex' = 'claude'): StructuredSession { + const session = { host: {}, identity: { sessionId: SESSION, agent } } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: delivery reads only identity.sessionId/agent, and the mocked send ignores host. + return session as unknown as StructuredSession +} + +const args = { + dispatchId: 'ctx_1', + dispatchDepth: 1, + taskId: 'task_1', + taskSpec: 'do it', + coordinatorHandle: 'session:7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64', + dispatchCapability: 'cap', + devMode: false, + requestId: 'req_1' +} + +describe('deliverWorkerDispatchPreamble tells each worker its own address', () => { + beforeEach(() => { + sent.preambles = [] + }) + + it('names a structured worker by the session it was started as', async () => { + const prompts: string[] = [] + await deliverWorkerDispatchPreamble({ + ...args, + runtime: runtime(prompts), + terminalHandle: 'structworker_1', + structuredSession: structuredSession() + }) + + expect(prompts).toEqual([]) + expect(sent.preambles).toHaveLength(1) + expect(sent.preambles[0]).toContain(`Your orchestration address is: session:${SESSION}\n`) + expect(sent.preambles[0]).toContain( + '"$ORCA_CLI_COMMAND" orchestration send --from structworker_1' + ) + }) + + it("renders the CLI in the worker's own shell: PowerShell for Codex on Windows", async () => { + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + try { + for (const agent of ['codex', 'claude'] as const) { + await deliverWorkerDispatchPreamble({ + ...args, + runtime: runtime([]), + terminalHandle: 'structworker_1', + structuredSession: structuredSession(agent) + }) + } + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + + expect(sent.preambles[0]).toContain('& $env:ORCA_CLI_COMMAND orchestration send') + expect(sent.preambles[1]).toContain('"$ORCA_CLI_COMMAND" orchestration send') + }) + + it('names a terminal worker by its handle and keeps its bare CLI', async () => { + const prompts: string[] = [] + await deliverWorkerDispatchPreamble({ + ...args, + runtime: runtime(prompts), + terminalHandle: 'term_worker', + structuredSession: null + }) + + expect(sent.preambles).toEqual([]) + expect(prompts[0]).toContain('Your orchestration address is: term_worker\n') + expect(prompts[0]).toContain('orca orchestration send --from term_worker') + expect(prompts[0]).not.toContain('ORCA_CLI_COMMAND') + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts index ecb3270874e..415773f00c7 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts @@ -4,6 +4,7 @@ import { buildDispatchPreamble, dispatchPreambleSendOptions } from '../../../../orchestration/preamble' +import { structuredSessionCliInvocation } from '../../../../orchestration/cli-command' import { sendStructuredWorkerPreamble } from '../../orchestration-structured-worker-session' import type { createStructuredWorkerSessionForWorktree } from './worker-topology' @@ -40,6 +41,18 @@ export async function deliverWorkerDispatchPreamble(args: { taskSpec: args.taskSpec, coordinatorHandle: args.coordinatorHandle, workerHandle: terminalHandle, + ...(structuredSession + ? { + structuredSession: { + sessionId: structuredSession.identity.sessionId, + cliInvocation: structuredSessionCliInvocation({ + platform: process.platform, + // Registered with its agent at start; null only for an entry rehydrated later. + provider: structuredSession.identity.agent ?? 'claude' + }) + } + } + : {}), dispatchCapability: args.dispatchCapability, devMode: args.devMode, cliCommand: runtime.getTerminalOrchestrationCliCommand(terminalHandle) diff --git a/src/main/runtime/rpc/orchestration-caller-show.test.ts b/src/main/runtime/rpc/orchestration-caller-show.test.ts new file mode 100644 index 00000000000..f246b0b9249 --- /dev/null +++ b/src/main/runtime/rpc/orchestration-caller-show.test.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as CODES } from '../../../shared/orchestration-session-caller-codes' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} from '../structured-worker-identity' +import { + ACTOR_X, + createSessionCallerHarness, + orchestrationRequest, + PROVIDER_ID_X, + resultOf, + SESSION_X, + SESSION_Y, + sessionRecord, + type SessionCallerHarness +} from './orchestration-session-caller-test-fixture' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock('../../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => hostRef.current +})) + +describe('orchestration.callerShow: the caller learns its own address from the host', () => { + let h: SessionCallerHarness + + beforeEach(() => { + h = createSessionCallerHarness(hostRef) + }) + + afterEach(() => { + h.close() + vi.restoreAllMocks() + }) + + function callerShow(options: Parameters[2]) { + return orchestrationRequest('orchestration.callerShow', {}, options) + } + + it('answers a chat with session:, even in terminal view where it also carries a pane', async () => { + const response = await h.dispatch( + callerShow({ + sessionId: SESSION_X, + evidence: { terminalHandle: 'term_tui', paneKey: 'tab_tui:1:2' } + }) + ) + + expect(resultOf(response)).toEqual({ + caller: { kind: 'session', address: ACTOR_X, sessionId: SESSION_X, live: true } + }) + }) + + it('answers a structured worker with its session address, not the handle it was minted', async () => { + const handle = mintStructuredWorkerHandle() + structuredWorkerIdentities.register({ + handle, + sessionId: SESSION_Y, + agent: 'claude', + paneKey: mintStructuredWorkerPaneKey(SESSION_Y), + processIncarnation: structuredWorkerProcessIncarnation(SESSION_Y), + worktreeId: 'wt_1', + hostScope: { kind: 'local', hostId: 'local' } + }) + + const response = await h.dispatch( + callerShow({ sessionId: SESSION_Y, evidence: { terminalHandle: handle } }) + ) + + expect(resultOf(response)).toEqual({ + caller: { kind: 'session', address: `session:${SESSION_Y}`, sessionId: SESSION_Y, live: true } + }) + }) + + it('refuses a session that is not running, with the same code every orchestration verb gets', async () => { + h.records.set(SESSION_X, sessionRecord(SESSION_X, { lease: { claimStatus: 'released' } })) + + const response = await h.dispatch(callerShow({ sessionId: SESSION_X })) + + expect(response).toMatchObject({ + ok: false, + error: { code: CODES.notLive, message: expect.stringContaining(SESSION_X) } + }) + }) + + it("names the Orca id when handed the provider's id", async () => { + const response = await h.dispatch(callerShow({ sessionId: PROVIDER_ID_X })) + + expect(response).toMatchObject({ + ok: false, + error: { code: CODES.providerId, data: { orcaSessionId: SESSION_X } } + }) + }) + + it('refuses a session claim from a paired client, naming the host boundary', async () => { + const response = await h.dispatchStreaming(callerShow({ sessionId: SESSION_X }), 'paired-1') + + expect(response).toMatchObject({ ok: false, error: { code: CODES.hostBoundary } }) + }) + + it('answers a terminal agent with the handle its environment carries, and whether it is live', async () => { + const probe = vi + .spyOn(h.runtime, 'resolveTerminalIdentity') + .mockImplementation((handle) => ({ handle, live: handle === 'term_live' })) + + const live = await h.dispatch(callerShow({ evidence: { terminalHandle: 'term_live' } })) + const stale = await h.dispatch(callerShow({ evidence: { terminalHandle: 'term_stale' } })) + + expect(resultOf(live)).toEqual({ + caller: { kind: 'terminal', address: 'term_live', live: true } + }) + expect(resultOf(stale)).toEqual({ + caller: { kind: 'terminal', address: 'term_stale', live: false } + }) + expect(probe).toHaveBeenCalledTimes(2) + }) + + it('answers null for a caller whose environment carries no identity', async () => { + const response = await h.dispatch(callerShow({})) + + expect(resultOf(response)).toEqual({ caller: null }) + }) +}) diff --git a/src/main/runtime/rpc/orchestration-session-caller.test.ts b/src/main/runtime/rpc/orchestration-session-caller.test.ts index c23bd9087bc..310c8bf30a9 100644 --- a/src/main/runtime/rpc/orchestration-session-caller.test.ts +++ b/src/main/runtime/rpc/orchestration-session-caller.test.ts @@ -92,8 +92,8 @@ describe('orchestration session callers at the dispatch entry', () => { .map((method) => method.name) .sort() - // The population: 41 registered methods, 21 of which carry a party-naming field. - expect(registry.size).toBe(41) + // The population: 42 registered methods, 21 of which carry a party-naming field. + expect(registry.size).toBe(42) expect(partyNaming).toHaveLength(21) expect(partyNaming).toEqual( [ diff --git a/src/renderer/src/components/native-chat/NativeChatCopyAddressMenuItem.tsx b/src/renderer/src/components/native-chat/NativeChatCopyAddressMenuItem.tsx new file mode 100644 index 00000000000..ffbb2b0c86e --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatCopyAddressMenuItem.tsx @@ -0,0 +1,39 @@ +import { Copy } from 'lucide-react' +import { toast } from 'sonner' +import { DropdownMenuItem } from '@/components/ui/dropdown-menu' +import { translate } from '@/i18n/i18n' + +/** + * Copies the session's orchestration address (`session:`), the Orca-minted id other agents + * message it by. Distinct from "Copy Session ID", which copies the provider's id and changes on + * `/clear`. + */ +export function NativeChatCopyAddressMenuItem({ address }: { address: string }): React.JSX.Element { + const copyAddress = async (): Promise => { + try { + await window.api.ui.writeClipboardText(address) + toast.success( + translate( + 'components.native-chat.contextMenu.orchestrationAddressCopied', + 'Orchestration address copied' + ) + ) + } catch { + toast.error( + translate( + 'components.native-chat.contextMenu.orchestrationAddressCopyFailed', + 'Unable to copy orchestration address' + ) + ) + } + } + return ( + void copyAddress()}> + + {translate( + 'components.native-chat.contextMenu.copyOrchestrationAddress', + 'Copy Orchestration Address' + )} + + ) +} diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 6a49cdfa12d..a10edb14414 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -2,6 +2,10 @@ import { useMemo, useRef, useState } from 'react' import { encodeAgentSessionQuestionAnswers } from '../../../../shared/agent-session-question-answer' import { dispatchStructuredAgentSessionComposerCommand } from '../../../../shared/structured-agent-session-composer' import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' +import { + formatOrchestrationActor, + sessionOrchestrationActor +} from '../../../../shared/orchestration-actor' import type { NativeChatLiveSession } from './use-native-chat-live-session' import { NativeChatApprovalCard } from './NativeChatApprovalCard' import { NativeChatComposer, type NativeChatComposerHandle } from './NativeChatComposer' @@ -60,13 +64,18 @@ export function NativeChatStructuredSession( ) const rootRef = useRef(null) const composerRef = useRef(null) + const orchestrationAddress = useMemo(() => { + const actor = sessionOrchestrationActor(props.sessionId) + return actor ? formatOrchestrationActor(actor) : undefined + }, [props.sessionId]) const paneCommands = useStructuredNativeChatPaneCommands({ tabId: props.tabId, groupId: props.groupId, isVisible: props.isVisible, rootRef, composerRef, - terminalPaneActions: props.contextMenuActions + terminalPaneActions: props.contextMenuActions, + orchestrationAddress }) const session = useMemo( () => ({ diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.test.tsx index 14841e6c56d..26ec5550c21 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.test.tsx @@ -53,6 +53,9 @@ vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +const toasts = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() })) +vi.mock('sonner', () => ({ toast: toasts })) + vi.mock('@/components/tab-bar/TabWorkspaceLayoutMenuSection', () => ({ TabWorkspaceLayoutMenuSection: () => 'Move Tab to Split' })) @@ -73,11 +76,15 @@ function childrenText(children: ReactNode): string { function Harness({ onSwitchToTerminal, structured = false, - enabled = true + enabled = true, + orchestrationAddress, + canCopyAgentSessionId = false }: { onSwitchToTerminal?: () => void structured?: boolean enabled?: boolean + orchestrationAddress?: string + canCopyAgentSessionId?: boolean }) { const rootRef = createRef() const { menu } = useNativeChatContextMenu({ @@ -86,8 +93,10 @@ function Harness({ onSwitchToTerminal, showTerminalPaneActions: !structured, workspaceLayout: structured ? { unifiedTabId: 'chat-tab', groupId: 'group-1' } : undefined, + orchestrationAddress, actions: { ...emptyNativeChatContextMenuActions, + canCopyAgentSessionId, onPaste: vi.fn() } satisfies NativeChatContextMenuActions }) @@ -155,4 +164,63 @@ describe('useNativeChatContextMenu', () => { document.dispatchEvent(new Event('selectionchange')) expect(getSelection).not.toHaveBeenCalled() }) + + describe('Copy Orchestration Address', () => { + const address = 'session:4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37' + const writeClipboardText = vi.fn() + + beforeEach(() => { + writeClipboardText.mockReset().mockResolvedValue(undefined) + toasts.success.mockReset() + toasts.error.mockReset() + Object.assign(window, { api: { ui: { writeClipboardText } } }) + }) + + function labels(): string[] { + return items.list.map((candidate) => childrenText(candidate.children)) + } + + function addressItem(): ItemProps | undefined { + return items.list.find( + (candidate) => childrenText(candidate.children) === 'Copy Orchestration Address' + ) + } + + it.each([ + ['a chat tab', true], + ['a chat in a terminal pane', false] + ])('copies session: in %s', async (_where, structured) => { + renderToStaticMarkup() + + addressItem()?.onSelect?.() + + await vi.waitFor(() => expect(toasts.success).toHaveBeenCalledOnce()) + expect(writeClipboardText).toHaveBeenCalledWith(address) + }) + + it('keeps the provider-id action beside it, under its own label', () => { + renderToStaticMarkup() + + expect(labels()).toEqual( + expect.arrayContaining(['Copy Orchestration Address', 'Copy Session ID']) + ) + }) + + it('is absent for a chat with no orchestration address', () => { + renderToStaticMarkup() + renderToStaticMarkup() + + expect(labels()).not.toContain('Copy Orchestration Address') + }) + + it('reports a failed copy instead of claiming success', async () => { + writeClipboardText.mockRejectedValue(new Error('denied')) + renderToStaticMarkup() + + addressItem()?.onSelect?.() + + await vi.waitFor(() => expect(toasts.error).toHaveBeenCalledOnce()) + expect(toasts.success).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.tsx index 48d896d4aea..058a8ad010d 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.tsx @@ -31,6 +31,7 @@ import { import { translate } from '@/i18n/i18n' import { isMacPlatform, nativeChatToggleShortcutLabel } from './native-chat-shortcut' import { TabWorkspaceLayoutMenuSection } from '@/components/tab-bar/TabWorkspaceLayoutMenuSection' +import { NativeChatCopyAddressMenuItem } from './NativeChatCopyAddressMenuItem' import type { TabSplitDirection } from '@/store/slices/tabs' type NativeChatContextMenuState = { @@ -52,6 +53,8 @@ type UseNativeChatContextMenuArgs = { groupId: string shortcutLabels?: Partial> } + /** A structured session's `session:`; terminal-backed chats are addressed by their handle. */ + orchestrationAddress?: string } export type NativeChatContextMenuActions = { @@ -103,7 +106,8 @@ export function useNativeChatContextMenu({ actions, showTerminalPaneActions = true, splitShortcutLabels, - workspaceLayout + workspaceLayout, + orchestrationAddress }: UseNativeChatContextMenuArgs): { onContextMenuCapture: MouseEventHandler onSelectionCapture: () => void @@ -284,6 +288,9 @@ export function useNativeChatContextMenu({ 'Set Title…' )} + {orchestrationAddress ? ( + + ) : null} {actions.canCopyAgentSessionId ? ( @@ -320,6 +327,11 @@ export function useNativeChatContextMenu({ ) : null} + ) : orchestrationAddress ? ( + <> + + + ) : null} diff --git a/src/renderer/src/components/native-chat/use-structured-native-chat-pane-commands.ts b/src/renderer/src/components/native-chat/use-structured-native-chat-pane-commands.ts index d479c6ac03a..0695f564861 100644 --- a/src/renderer/src/components/native-chat/use-structured-native-chat-pane-commands.ts +++ b/src/renderer/src/components/native-chat/use-structured-native-chat-pane-commands.ts @@ -18,7 +18,8 @@ export function useStructuredNativeChatPaneCommands({ isVisible, rootRef, composerRef, - terminalPaneActions + terminalPaneActions, + orchestrationAddress }: { tabId: string groupId?: string @@ -26,6 +27,7 @@ export function useStructuredNativeChatPaneCommands({ rootRef: RefObject composerRef: RefObject terminalPaneActions?: Omit + orchestrationAddress?: string }) { const keybindings = useAppStore((state) => state.keybindings) const pasteClipboardIntoComposer = useNativeChatPasteBridge({ rootRef, composerRef }) @@ -37,6 +39,7 @@ export function useStructuredNativeChatPaneCommands({ onPaste: pasteClipboardIntoComposer }, enabled: isVisible, + orchestrationAddress, showTerminalPaneActions: terminalPaneActions !== undefined, splitShortcutLabels: { right: formatShortcutLabel('terminal.splitRight', keybindings), diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 7284c8b41e8..01722619cd5 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -17735,6 +17735,11 @@ "label": "Context {{used}} of {{window}} tokens, {{percent}}% used", "title": "Context", "estimated": "Estimated from the last response." + }, + "contextMenu": { + "orchestrationAddressCopied": "Orchestration address copied", + "orchestrationAddressCopyFailed": "Unable to copy orchestration address", + "copyOrchestrationAddress": "Copy Orchestration Address" } }, "tab": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index cfce4be274b..0b70a4d35d1 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14796,7 +14796,12 @@ "allow": "Permitir", "deny": "Denegar" }, - "launchPromptNotDelivered": "No entregado — revisa la terminal" + "launchPromptNotDelivered": "No entregado — revisa la terminal", + "contextMenu": { + "orchestrationAddressCopied": "Dirección de orquestación copiada", + "orchestrationAddressCopyFailed": "No se pudo copiar la dirección de orquestación", + "copyOrchestrationAddress": "Copiar dirección de orquestación" + } }, "tab": { "bar": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 3bb3ca43922..790d79bd321 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -16142,7 +16142,12 @@ "allow": "Autoriser", "deny": "Refuser" }, - "launchPromptNotDelivered": "Non livré — vérifiez le terminal" + "launchPromptNotDelivered": "Non livré — vérifiez le terminal", + "contextMenu": { + "orchestrationAddressCopied": "Adresse d'orchestration copiée", + "orchestrationAddressCopyFailed": "Impossible de copier l'adresse d'orchestration", + "copyOrchestrationAddress": "Copier l'adresse d'orchestration" + } }, "tab": { "bar": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index db72c535817..f45e66b5e40 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14831,7 +14831,12 @@ "allow": "許可する", "deny": "拒否" }, - "launchPromptNotDelivered": "配信されませんでした — ターミナルを確認してください" + "launchPromptNotDelivered": "配信されませんでした — ターミナルを確認してください", + "contextMenu": { + "orchestrationAddressCopied": "オーケストレーションアドレスをコピーしました", + "orchestrationAddressCopyFailed": "オーケストレーションアドレスのコピーに失敗しました", + "copyOrchestrationAddress": "オーケストレーションアドレスをコピー" + } }, "tab": { "bar": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 55893501e49..b4601c83988 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -14908,7 +14908,12 @@ "allow": "허용", "deny": "거부" }, - "launchPromptNotDelivered": "전달되지 않음 — 터미널을 확인하세요" + "launchPromptNotDelivered": "전달되지 않음 — 터미널을 확인하세요", + "contextMenu": { + "orchestrationAddressCopied": "오케스트레이션 주소를 복사했습니다", + "orchestrationAddressCopyFailed": "오케스트레이션 주소를 복사하지 못했습니다", + "copyOrchestrationAddress": "오케스트레이션 주소 복사" + } }, "tab": { "bar": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 2f5c569a099..865c10c8a28 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -14876,7 +14876,12 @@ "allow": "允许", "deny": "拒绝" }, - "launchPromptNotDelivered": "未送达 — 请检查终端" + "launchPromptNotDelivered": "未送达 — 请检查终端", + "contextMenu": { + "orchestrationAddressCopied": "已复制编排地址", + "orchestrationAddressCopyFailed": "复制编排地址失败", + "copyOrchestrationAddress": "复制编排地址" + } }, "tab": { "bar": { diff --git a/src/shared/orchestration-caller-status.ts b/src/shared/orchestration-caller-status.ts new file mode 100644 index 00000000000..38d28bcdb89 --- /dev/null +++ b/src/shared/orchestration-caller-status.ts @@ -0,0 +1,36 @@ +/** + * The calling agent's own orchestration address, as the host resolved it from the identity injected + * into the caller's environment: its Orca session id, else its terminal handle. Never from a flag. + * `orca status --json` reports it as `caller`, so any agent can learn the address others reach it by. + */ +export type OrchestrationCallerAddress = + | { + kind: 'session' + /** `session:`: one spelling for every session, a structured worker included. */ + address: string + sessionId: string + /** The host resolves a session only while its lease is live; otherwise it refuses. */ + live: true + } + | { + kind: 'terminal' + address: string + /** False for a handle this process kept across a remint or a window reload. */ + live: boolean + } + +/** The host refused the session this process names, so it cannot act as it right now. */ +export type OrchestrationCallerRefusal = { + kind: 'session' + sessionId: string + live: false + refusal: { code: string; message: string } +} + +/** + * `null`: this process carries no orchestration identity. Absent from a status result: nothing was + * resolved, because the runtime was unreachable or the host predates `orchestration.callerShow`. + */ +export type CliStatusCaller = OrchestrationCallerAddress | OrchestrationCallerRefusal | null + +export type OrchestrationCallerShowResult = { caller: OrchestrationCallerAddress | null } diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 2cd61678c28..c07c68471e9 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -979,6 +979,7 @@ export const RPC_PARAMS_BY_METHOD = { 'notifications.unregisterPush': null, 'notifications.unsubscribe': NotificationUnsubscribeParams, 'orchestration.ask': AskParams, + 'orchestration.callerShow': null, 'orchestration.check': CheckParams, 'orchestration.dispatch': DispatchParams, 'orchestration.dispatchShow': DispatchShowParams, diff --git a/src/shared/runtime-session-contracts.ts b/src/shared/runtime-session-contracts.ts index 393c95fec87..e70ad711468 100644 --- a/src/shared/runtime-session-contracts.ts +++ b/src/shared/runtime-session-contracts.ts @@ -14,6 +14,7 @@ import type { RuntimeMobileSessionSnapshotTab, RuntimeMobileSessionTerminalClientTab } from './runtime-mobile-session-tab-contracts' +import type { CliStatusCaller } from './orchestration-caller-status' export type * from './runtime-mobile-session-tab-contracts' @@ -127,6 +128,8 @@ export type CliStatusResult = { graph: { state: RuntimeGraphStatus | 'not_running' | 'starting' } + /** This process's orchestration address, resolved by the host; see `CliStatusCaller`. */ + caller?: CliStatusCaller } export type RuntimeSyncedTab = {