@ouro.bot/cli 0.1.0-alpha.1555 → 0.1.0-alpha.1557

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/changelog.json +12 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/desk.lock.json +3 -3
  5. package/dist/mind/diary.js +7 -3
  6. package/dist/repertoire/tools-notes.js +4 -0
  7. package/npm-shrinkwrap.json +2 -2
  8. package/package.json +1 -1
  9. package/vendor/desk/.claude-plugin/plugin.json +1 -1
  10. package/vendor/desk/.ouro-desk.json +3 -3
  11. package/vendor/desk/CHANGELOG.md +600 -0
  12. package/vendor/desk/activation/copilot-root.flattened-bundle.json +2 -2
  13. package/vendor/desk/activation/desk.activation.json +5 -5
  14. package/vendor/desk/agency.json +1 -1
  15. package/vendor/desk/docs/sessions.md +1 -1
  16. package/vendor/desk/hooks/lib/boot-checks.cjs +1 -1
  17. package/vendor/desk/hooks/lib/child-agent.cjs +2 -2
  18. package/vendor/desk/hooks/lib/factory-end.cjs +4 -1
  19. package/vendor/desk/mcp/README.md +6 -0
  20. package/vendor/desk/mcp/bootstrap.cjs +64 -38
  21. package/vendor/desk/mcp/idle-proxy.cjs +14 -6
  22. package/vendor/desk/mcp/scripts/crew.js +3 -3
  23. package/vendor/desk/mcp/scripts/drains-launcher.mjs +6 -5
  24. package/vendor/desk/mcp/scripts/factory.js +15 -6
  25. package/vendor/desk/mcp/scripts/resolve-desk-root.js +1 -2
  26. package/vendor/desk/mcp/src/actions/desk-session.actions.mts +16 -1
  27. package/vendor/desk/mcp/src/actions/desk.actions.mts +2 -2
  28. package/vendor/desk/mcp/src/actions/generated/desk/actions.json +36 -1
  29. package/vendor/desk/mcp/src/actions/generated/desk/mcp.json +34 -1
  30. package/vendor/desk/mcp/src/activation/superpowers-context.js +9 -0
  31. package/vendor/desk/mcp/src/crew/workspace.js +30 -4
  32. package/vendor/desk/mcp/src/desk/card-commit-guard.js +3 -2
  33. package/vendor/desk/mcp/src/desk/content-home.js +16 -0
  34. package/vendor/desk/mcp/src/indexer/discover.js +8 -0
  35. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-claims.ts +2 -1
  36. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/ax-command.ts +20 -0
  37. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/mcp.ts +1 -1
  38. package/vendor/desk/mcp/src/lib/ouro-ui/registry/ouro/ax/xray.ts +40 -2
  39. package/vendor/desk/mcp/src/runtime/boot.js +0 -1
  40. package/vendor/desk/mcp/src/runtime/deliver.js +42 -5
  41. package/vendor/desk/mcp/src/runtime/drains-cli.js +9 -1
  42. package/vendor/desk/mcp/src/runtime/drains.js +7 -4
  43. package/vendor/desk/mcp/src/runtime/hosted.js +5 -3
  44. package/vendor/desk/mcp/src/runtime/pending-migrations.js +5 -1
  45. package/vendor/desk/mcp/src/runtime/pr-publication.js +55 -29
  46. package/vendor/desk/mcp/src/runtime/relays.js +10 -1
  47. package/vendor/desk/mcp/src/runtime/remote-identity.js +22 -0
  48. package/vendor/desk/mcp/src/runtime/sessions-cli.js +6 -6
  49. package/vendor/desk/mcp/src/runtime/sync-worker.js +10 -8
  50. package/vendor/desk/mcp/src/runtime/unmerged-saves.js +29 -3
  51. package/vendor/desk/mcp/src/server.js +3 -2
  52. package/vendor/desk/mcp/src/tool-names.js +0 -2
  53. package/vendor/desk/mcp/src/tool-schemas.js +3 -8
  54. package/vendor/desk/mcp/src/tools/archive-links.js +3 -0
  55. package/vendor/desk/mcp/src/tools/desk-save.js +8 -3
  56. package/vendor/desk/mcp/src/tools/move.js +32 -3
  57. package/vendor/desk/mcp/src/tools/sibling-desk.js +10 -4
  58. package/vendor/desk/mcp/src/tools/status.js +9 -6
  59. package/vendor/desk/mcp/src/tools/task-log.js +6 -2
  60. package/vendor/desk/mcp/src/tools/task.js +17 -5
  61. package/vendor/desk/mcp/src/util/citations.js +54 -0
  62. package/vendor/desk/mcp/web-auth.cjs +17 -0
  63. package/vendor/desk/mcp/web-sso.cjs +52 -0
  64. package/vendor/desk/plugin.json +2 -2
  65. package/vendor/desk/skills/add-workspace-mcp/SKILL.md +2 -2
  66. package/vendor/desk/skills/archive-workflow/SKILL.md +1 -1
  67. package/vendor/desk/skills/coordinating-lanes/SKILL.md +24 -0
  68. package/vendor/desk/skills/evidence-discipline/SKILL.md +8 -12
  69. package/vendor/desk/skills/git-hygiene/SKILL.md +6 -0
  70. package/vendor/desk/skills/interaction-style/SKILL.md +4 -2
  71. package/vendor/desk/skills/live-ui-iteration/SKILL.md +35 -0
  72. package/vendor/desk/skills/operator-voice-comments/SKILL.md +4 -0
  73. package/vendor/desk/skills/outside-approval/SKILL.md +10 -0
  74. package/vendor/desk/skills/pr-feedback-on-own-pr/SKILL.md +5 -1
  75. package/vendor/desk/skills/pr-reviewer-audit/SKILL.md +1 -1
  76. package/vendor/desk/skills/pr-reviewer-audit/helpers/audit.py +19 -1
  77. package/vendor/desk/skills/pr-reviewer-audit/helpers/test_audit.py +37 -1
  78. package/vendor/desk/skills/pr-self-review/SKILL.md +1 -1
  79. package/vendor/desk/skills/pr-surface-hygiene/SKILL.md +28 -4
  80. package/vendor/desk/skills/pr-surface-hygiene/check-visual-proof.cjs +27 -14
  81. package/vendor/desk/skills/prior-art/SKILL.md +14 -0
  82. package/vendor/desk/skills/runtime-symptom-investigation/SKILL.md +5 -1
  83. package/vendor/desk/skills/session-resumption/SKILL.md +3 -1
  84. package/vendor/desk/skills/using-desk/SKILL.md +3 -3
  85. package/vendor/desk/skills/using-superpowers-with-desk/SKILL.md +2 -0
  86. package/vendor/desk/skills/visual-proof/SKILL.md +42 -0
  87. package/vendor/desk/skills/work-orchestration/SKILL.md +17 -2
@@ -1,4 +1,6 @@
1
+ import { spawnSync } from "node:child_process"
1
2
  import { fileURLToPath } from "node:url"
3
+ import { ghEnvFor } from "./remote-identity.js"
2
4
  import { shellQuote } from "../util/shell-quote.js"
3
5
  import { redactCredentialLikeText } from "../util/redact.js"
4
6
 
@@ -6,7 +8,7 @@ const OBJECT_ID = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u
6
8
 
7
9
  const POLICY = ".desk/publication.json"
8
10
  const FIELDS = "number,url,state,isDraft,headRefOid,baseRefName,baseRefOid,mergeCommit,mergeable"
9
- // The label a merge-when-green relay (runtime/relays.js) polls for; a policy may name another with `merge_label`.
11
+ // The default label a merge-when-green relay (runtime/relays.js) polls for.
10
12
  const MERGE_LABEL = "merge-when-green"
11
13
  const WAIT_MS = 300_000
12
14
  const CLOCK = {
@@ -67,6 +69,22 @@ export function publicationRecovery(root, platform = process.platform) {
67
69
  return `node ${commandArgument(script, platform)} --root ${commandArgument(root, platform)}`
68
70
  }
69
71
 
72
+ const QUOTA_REFUSAL = /rate limit|quota|calls left|secondary rate|HTTP 429/iu
73
+ const AUTH_REFUSAL = /gh auth|auth login|not logged in|authenticat|bad credentials|HTTP 401/iu
74
+
75
+ // Names the cause gh reported: a quota refusal is shown (its first line, redacted) because waiting fixes it, auth only when gh says so,
76
+ // and any other failure leaves subprocess output out, which can contain credentials.
77
+ function ghFailure(args, result, host) {
78
+ const what = `GitHub CLI ${args[0]} ${args[1]} failed (exit ${result.status ?? "timeout"})`
79
+ const stderr = String(result.stderr ?? "")
80
+ if (QUOTA_REFUSAL.test(stderr)) {
81
+ const line = redactCredentialLikeText(stderr.split("\n").find((text) => text.trim() !== "").trim()).slice(0, 300)
82
+ return Object.assign(new Error(`Wait for the GitHub API quota to recover, then try again: ${what} because the GitHub API quota is low; the account's auth is not the problem. gh said: ${line}`), { code: "pr_publication_wait_for_the_github_api_quota" })
83
+ }
84
+ if (AUTH_REFUSAL.test(stderr)) return Object.assign(new Error(`Check gh auth status, then try again: ${what}; check gh auth status --hostname ${host}`), { code: "pr_publication_check_gh_auth_status_then" })
85
+ return Object.assign(new Error(`Run it again: ${what}; run the same gh command by hand to see why`), { code: "pr_publication_run_it_again_github_cli_failed" })
86
+ }
87
+
70
88
  /** Publishes one immutable candidate. No upstream ref is pushed; only GitHub's exact-head merge endpoint can advance it. */
71
89
  export function publishPullRequest({ git, spawnGit, root, upstream, head, onto, policy, clock = CLOCK, track }) {
72
90
  // Both candidates must be object ids: a head or base that was never read would build a branch name, and a command, with nothing in them.
@@ -80,12 +98,13 @@ export function publishPullRequest({ git, spawnGit, root, upstream, head, onto,
80
98
  const repo = repository(remote.stdout.trim())
81
99
  const base = upstream.merge.replace(/^refs\/heads\//u, "")
82
100
  const branch = `desk/publish/${head}`
101
+ // `spawnGit` is a test seam over `spawnSync`; only the real one asks which account can reach the repository.
102
+ const [owner, repoName] = repo.name.split("/")
103
+ /* istanbul ignore next -- only the real spawnSync asks gh which account can reach the repository; tests inject a fake. */
104
+ const ghEnv = spawnGit === spawnSync ? ghEnvFor({ host: repo.host, owner, repo: repoName, env: process.env, spawn: spawnSync }) : process.env
83
105
  const gh = (args, json = true) => {
84
- const result = spawnGit("gh", args, { cwd: root, encoding: "utf8", windowsHide: true, timeout: 60_000, env: process.env })
85
- if (result.status !== 0) {
86
- // Do not echo arbitrary subprocess output, which can contain credentials.
87
- throw Object.assign(new Error(`Check gh auth status, then try again: GitHub CLI ${args[0]} ${args[1]} failed (exit ${result.status ?? "timeout"}); check gh auth status --hostname ${repo.host}`), { code: "pr_publication_check_gh_auth_status_then" })
88
- }
106
+ const result = spawnGit("gh", args, { cwd: root, encoding: "utf8", windowsHide: true, timeout: 60_000, env: ghEnv })
107
+ if (result.status !== 0) throw ghFailure(args, result, repo.host)
89
108
  if (!json) return result.stdout
90
109
  try { return JSON.parse(result.stdout) } catch { throw Object.assign(new Error("Run it again: GitHub CLI returned invalid publication JSON"), { code: "pr_publication_run_it_again_github_cli" }) }
91
110
  }
@@ -160,25 +179,7 @@ export function publishPullRequest({ git, spawnGit, root, upstream, head, onto,
160
179
  }
161
180
  if (pr === undefined) throw Object.assign(new Error("Run it again: The created publication PR could not be read back"), { code: "pr_publication_run_it_again_the_created" })
162
181
  const receipt = { url: pr.url, head, branch, base }
163
- // Each candidate has its own branch, so an earlier candidate's PR that never merged would stay open until someone closes it by hand. This one carries its work, so close the others; best effort.
164
- if (pr.state === "OPEN") {
165
- try {
166
- const open = gh(["pr", "list", "--repo", repo.full, "--base", base, "--state", "open", "--json", "number,headRefName"])
167
- for (const old of open) {
168
- if (!String(old.headRefName).startsWith("desk/publish/") || old.headRefName === branch) continue
169
- try { gh(["pr", "close", String(old.number), "--repo", repo.full, "--delete-branch", "--comment", `Superseded by ${pr.url}, which publishes a newer candidate that includes this one's work.`], false) } catch { /* the next publication tries again */ }
170
- }
171
- } catch { /* closing is housekeeping; it never blocks publishing */ }
172
- }
173
- // Merging must not depend on one repository setting: the relay's label goes on every publication PR, and auto-merge is asked for where the repository allows it. Both are best effort; the checks below still gate Desk's own merge.
174
- if (pr.state !== "MERGED") {
175
- const label = MERGE_LABEL
176
- const attempt = (args) => { try { gh(args, false); return true } catch { return false } }
177
- attempt(["label", "create", label, "--repo", repo.full, "--force", "--description", "Merge when the required checks are green"])
178
- receipt.labelled = attempt(["pr", "edit", String(pr.number), "--repo", repo.full, "--add-label", label])
179
- receipt.auto_merge = attempt(["pr", "merge", String(pr.number), "--repo", repo.full, "--auto", "--merge", "--match-head-commit", head]) ? "enabled" : "refused"
180
- track?.record(receipt)
181
- }
182
+ if (pr.state !== "MERGED") track?.record(receipt)
182
183
  const view = () => gh(["pr", "view", String(pr.number), "--repo", repo.full, "--json", FIELDS])
183
184
  const verify = (current) => {
184
185
  if (current.headRefOid !== head || current.baseRefName !== base || current.isDraft || !["OPEN", "MERGED"].includes(current.state)) {
@@ -199,14 +200,39 @@ export function publishPullRequest({ git, spawnGit, root, upstream, head, onto,
199
200
  const reported = loadChecks()
200
201
  const waiting = checkState(reported, policy.required_checks, observed, ruled)
201
202
  if (waiting.length === 0) {
202
- const merged = gh(["api", "--hostname", repo.host, "--method", "PUT", `repos/${repo.name}/pulls/${pr.number}/merge`,
203
- "-f", `sha=${head}`, "-f", "merge_method=merge"])
204
- if (merged.merged !== true || typeof merged.sha !== "string") throw Object.assign(new Error("Check the pull request's merge requirements, then run it again: GitHub refused the exact-head merge"), { code: "pr_publication_check_the_pull_request_s" })
205
- receipt.merge = merged.sha
203
+ // A relay label can trigger a merge too. Arm it only after policy qualification; gh --auto can merge immediately.
204
+ const attempt = (args) => { try { gh(args, false); return true } catch { return false } }
205
+ attempt(["label", "create", MERGE_LABEL, "--repo", repo.full, "--force", "--description", "Merge when the required checks are green"])
206
+ try {
207
+ // gh pr edit uses GraphQL, which an otherwise working repository token may not be allowed to use.
208
+ const labels = gh(["api", "--hostname", repo.host, "--method", "POST", `repos/${repo.name}/issues/${pr.number}/labels`,
209
+ "-f", `labels[]=${MERGE_LABEL}`])
210
+ if (!Array.isArray(labels) || !labels.some((label) => label?.name === MERGE_LABEL)) {
211
+ throw Object.assign(new Error("Check the PR's labels, then retry publication: the merge relay label was not confirmed by GitHub"), { code: "pr_publication_relay_label_unconfirmed" })
212
+ }
213
+ receipt.labelled = true
214
+ } catch (error) {
215
+ receipt.labelled = false
216
+ receipt.label_error = error.message
217
+ }
218
+ try {
219
+ const merged = gh(["api", "--hostname", repo.host, "--method", "PUT", `repos/${repo.name}/pulls/${pr.number}/merge`,
220
+ "-f", `sha=${head}`, "-f", "merge_method=merge"])
221
+ if (merged.merged !== true || typeof merged.sha !== "string") throw Object.assign(new Error("Check the pull request's merge requirements, then run it again: GitHub refused the exact-head merge"), { code: "pr_publication_check_the_pull_request_s" })
222
+ receipt.merge = merged.sha
223
+ } catch (error) {
224
+ pr = view()
225
+ verify(pr)
226
+ if (pr.state !== "MERGED") {
227
+ if (!receipt.labelled) error.message += `. The merge relay label was not confirmed: ${receipt.label_error}`
228
+ throw error
229
+ }
230
+ }
206
231
  break
207
232
  }
208
233
  if (clock.now() >= deadline) {
209
234
  const unreported = policy.required_checks.filter((name) => !reported.some((check) => check.name === name))
235
+ receipt.pending_checks = true
210
236
  throw Object.assign(new Error(`Wait for the checks to finish, then run it again: PR checks still missing or pending: ${waiting.join(", ")}${unreported.length === 0 ? "" : `. Never reported on ${head}: ${unreported.join(", ")}. GitHub Actions will not supply a check that is only posted by running it against this exact commit (for example CIT's cit-check, which runs on a writer's machine); run it on branch ${branch}`}`), { code: "pr_publication_wait_for_the_checks_to" })
211
237
  }
212
238
  clock.sleep(Math.min(5000, deadline - clock.now()))
@@ -873,6 +873,7 @@ export async function pollRelays({ paths, drainFiles, connect, now, signedIn = (
873
873
  if (login) state.resolvedAccount = login
874
874
  } catch (error) {
875
875
  state.lastError = error.message
876
+ keepCode(state, error)
876
877
  state.lastPollAt = new Date(now).toISOString()
877
878
  return
878
879
  }
@@ -901,8 +902,10 @@ export async function pollRelays({ paths, drainFiles, connect, now, signedIn = (
901
902
  forget(state, ctx.touched)
902
903
  state.lastOkAt = new Date(now).toISOString()
903
904
  delete state.lastError
905
+ delete state.lastErrorCode
904
906
  } catch (error) {
905
907
  state.lastError = error.message
908
+ keepCode(state, error)
906
909
  // A refusal means the remembered account cannot reach the repository (any more): choose again next poll.
907
910
  if (state.resolvedAccount && [401, 403, 404].includes(error.status)) delete state.resolvedAccount
908
911
  }
@@ -915,10 +918,16 @@ export async function pollRelays({ paths, drainFiles, connect, now, signedIn = (
915
918
  const apis = await Promise.all([...connections.values()].map((connection) => connection.catch(() => null)))
916
919
  const calls = apis.reduce((sum, api) => sum + (api ? api.calls().total : 0), 0)
917
920
  const spent = relays.reduce((sum, relay) => sum + (states[relay.name].lastPoll?.at === new Date(now).toISOString() ? states[relay.name].lastPoll.counted : 0), 0)
918
- const errors = relays.filter((relay) => states[relay.name].lastError).map((relay) => ({ relay: relay.name, error: states[relay.name].lastError }))
921
+ const errors = relays.filter((relay) => states[relay.name].lastError).map((relay) => ({ relay: relay.name, error: states[relay.name].lastError, ...(states[relay.name].lastErrorCode ? { code: states[relay.name].lastErrorCode } : {}) }))
919
922
  return { at: new Date(now).toISOString(), wakes: [], errors, calls, spent, status: relayStatusLines(relays, states, now) }
920
923
  }
921
924
 
925
+ /** Keep the failure's stable code beside its text, so a runner can branch on it. */
926
+ function keepCode(state, error) {
927
+ if (typeof error.code === "string") state.lastErrorCode = error.code
928
+ else delete state.lastErrorCode
929
+ }
930
+
922
931
  // ── Visibility ──
923
932
 
924
933
  function span(ms) {
@@ -100,6 +100,28 @@ function canUse({ host, login, owner, repo, push, env, spawn, cache, now }) {
100
100
  })
101
101
  }
102
102
 
103
+ /**
104
+ * `env` for a `gh` command about one repository. The Copilot app's `gh` has whichever account is active, which is not
105
+ * always the one that can reach the repository, and the `gh` wrapper that picks by owner is not always on the PATH Desk
106
+ * runs under. When no token variable is set and a signed-in account can push to the repository (else read it), the result
107
+ * carries that account's token for `gh`; otherwise it is `env` itself.
108
+ */
109
+ /* istanbul ignore next -- the defaults are the real cache and clock; tests inject both. */
110
+ export function ghEnvFor({ host, owner, repo, env, spawn, cache = lookupCache, now = Date.now }) {
111
+ if (TOKEN_VARIABLES.some((name) => name !== "GH_HOST" && (env[name] ?? "") !== "")) return env
112
+ if (!HOST.test(host) || !LOGIN.test(owner) || !REPO.test(repo)) return env
113
+ const candidates = [...new Set([owner, ...signedInLogins({ host, env, spawn, cache, now })])].filter((login) => LOGIN.test(login))
114
+ for (const push of [true, false]) {
115
+ for (const login of candidates) {
116
+ if (!canUse({ host, login, owner, repo, push, env, spawn, cache, now })) continue
117
+ const token = tokenFor({ host, login, env, spawn })
118
+ if (token === "") continue
119
+ return host === "github.com" ? { ...env, GH_TOKEN: token } : { ...env, GH_ENTERPRISE_TOKEN: token, GH_HOST: host }
120
+ }
121
+ }
122
+ return env
123
+ }
124
+
103
125
  function gitText(spawn, root, args, env) {
104
126
  const result = (spawn === spawnSync ? fastGitAnswer(root, args) : null) ?? spawn("git", ["-C", root, ...args], { windowsHide: true, encoding: "utf8", timeout: LOOKUP_TIMEOUT_MS, env })
105
127
  return result.status === 0 ? result.stdout.trim() : ""
@@ -229,7 +229,7 @@ async function seenWithin(seen, waitMs, { sleep, now }) {
229
229
  async function runSend({ ref, message, from: fromFlag, asUser, waitMs, script, deps }) {
230
230
  const target = resolveSession(deps.stateDir, ref)
231
231
  if (target.reason !== undefined) {
232
- throw failure("sessions_target", `cannot send to ${JSON.stringify(ref)}`, target.reason, "run sessions.js tail <id or name> to check the session, or ask the person which one is meant", "pass the full session id")
232
+ throw failure("sessions-target", `cannot send to ${JSON.stringify(ref)}`, target.reason, "run sessions.js tail <id or name> to check the session, or ask the person which one is meant", "pass the full session id")
233
233
  }
234
234
  const nonce = deps.nonce()
235
235
  let prompt = message
@@ -244,13 +244,13 @@ async function runSend({ ref, message, from: fromFlag, asUser, waitMs, script, d
244
244
  const before = new Set(tailMessages(readHistoryTail(deps.stateDir, target.id)?.text ?? "", 20).map((entry) => entry.at))
245
245
  const socket = deps.socket()
246
246
  if (socket.reason !== undefined) {
247
- throw failure("sessions_app_socket", "cannot reach the GitHub Copilot app", socket.reason, "check that the app is open, then run sessions.js tail on the target to see whether the message arrived another way", "start the app and run the same command again")
247
+ throw failure("sessions-app-socket", "cannot reach the GitHub Copilot app", socket.reason, "check that the app is open, then run sessions.js tail on the target to see whether the message arrived another way", "start the app and run the same command again")
248
248
  }
249
249
  const result = await deps.send({ id: target.id, prompt, socket })
250
250
  const matches = (entry) => entry.role === "user" && (asUser ? entry.text.trim() === message.trim().slice(0, MESSAGE_CHARS) && !before.has(entry.at) : entry.text.includes(`[Message ${nonce} `))
251
251
  const delivered = result.accepted && (await seenWithin(() => tailMessages(readHistoryTail(deps.stateDir, target.id)?.text ?? "", 20).some(matches), waitMs, deps))
252
252
  if (!result.accepted) {
253
- throw failure("sessions_send_refused", `the app did not accept the message for ${target.id}`, result.error ?? `the app answered ${result.reply}; the session may be archived or not a Copilot app session`, `run sessions.js tail ${target.id} to see the session`, "pass the id of a session that is open in the app")
253
+ throw failure("sessions-send-refused", `the app did not accept the message for ${target.id}`, result.error ?? `the app answered ${result.reply}; the session may be archived or not a Copilot app session`, `run sessions.js tail ${target.id} to see the session`, "pass the id of a session that is open in the app")
254
254
  }
255
255
  const note = delivered ? undefined : `The app accepted the message but it was not in the history after ${waitMs / 1000} s. Read it with sessions.js tail ${target.id} before sending again, so it is not sent twice.`
256
256
  return { to: target.id, from: sender, nonce: asUser ? null : nonce, accepted: true, delivered, reply: result.reply, ...(note === undefined ? {} : { note }) }
@@ -267,17 +267,17 @@ function sessionsCli({ script, deps, overrides }) {
267
267
  commands: [
268
268
  command("whoami", { readOnly: true, summary: "Print the session this command runs in. With several sessions in one runtime, --hint <text from your own command> picks yours.", flags: { hint: { type: "string", description: "Text from your own command line, which is in your session's history." } } }, (input) => {
269
269
  if (deps.platform === "win32" && overrides.self === undefined) {
270
- throw failure("sessions_whoami_platform", "whoami cannot walk process parents here", "this command reads the process tree with ps, which Windows does not have", "read your own session id from the session folder name or the app", "pass --from <your session id> to send instead")
270
+ throw failure("sessions-whoami-platform", "whoami cannot walk process parents here", "this command reads the process tree with ps, which Windows does not have", "read your own session id from the session folder name or the app", "pass --from <your session id> to send instead")
271
271
  }
272
272
  return whoAmI(deps.stateDir, input.hint ?? null, deps.self)
273
273
  }),
274
274
  command("tail", { readOnly: true, summary: "Print the last <count> (default 6) user and assistant messages of a session.", args: [SESSION, { name: "count", description: "How many messages, a positive whole number." }] }, (input) => {
275
275
  const count = input.count === undefined ? 6 : Number(input.count)
276
- if (!Number.isInteger(count) || count < 1) throw new AxError({ code: "sessions_tail_count", exit: 2, thing: "tail", problem: `the count must be a positive whole number, not ${JSON.stringify(input.count)}`, fix: "run sessions tail <session> [<count>]" })
276
+ if (!Number.isInteger(count) || count < 1) throw new AxError({ code: "sessions-tail-count", exit: 2, thing: "tail", problem: `the count must be a positive whole number, not ${JSON.stringify(input.count)}`, fix: "run sessions tail <session> [<count>]" })
277
277
  const target = resolveSession(deps.stateDir, input.session)
278
278
  const history = target.reason !== undefined ? null : readHistoryTail(deps.stateDir, target.id)
279
279
  if (target.reason !== undefined || history === null) {
280
- throw failure("sessions_tail_target", `cannot read ${JSON.stringify(input.session)}`, target.reason ?? `session ${target.id} has no events.jsonl here, so it is on another machine or has been removed`, "check the id or name, or run the command on the machine that hosts the session", "pass the full session id")
280
+ throw failure("sessions-tail-target", `cannot read ${JSON.stringify(input.session)}`, target.reason ?? `session ${target.id} has no events.jsonl here, so it is on another machine or has been removed`, "check the id or name, or run the command on the machine that hosts the session", "pass the full session id")
281
281
  }
282
282
  return { id: target.id, name: nameOf(deps.stateDir, target.id), last_written: history.mtime, messages: tailMessages(history.text, count) }
283
283
  }),
@@ -621,10 +621,10 @@ async function upstreamBack({ root, spawnGit, clock }) {
621
621
  return false
622
622
  }
623
623
 
624
- async function deliverUntilDone({ root, env, spawnGit, fileProblem, clock }) {
624
+ async function deliverUntilDone({ root, env, spawnGit, fileProblem, clock, publicationClock }) {
625
625
  let pushedAt = null
626
626
  // Publication PRs still waiting from earlier saves are settled first: closed when superseded, rebuilt when they conflict with main.
627
- settleSaves({ root, env, spawnGit })
627
+ settleSaves({ root, env, spawnGit, clock: publicationClock })
628
628
  for (let round = 0; round < MAX_ROUNDS; round += 1) {
629
629
  const delivered = deliveredSoFar(root, env)
630
630
  const pending = undeliveredCommits({ root, spawnGit, delivered })
@@ -633,7 +633,7 @@ async function deliverUntilDone({ root, env, spawnGit, fileProblem, clock }) {
633
633
  updateSyncStatus(root, env, { blocked: false, reason: null, paths: [], unpushed: 0, error: null, ...(pushedAt === null ? {} : { last_push_at: pushedAt, last_pull: null }) })
634
634
  return { result: "ok" }
635
635
  }
636
- const outcome = deliver({ root, env, spawnGit, delivered })
636
+ const outcome = deliver({ root, env, spawnGit, delivered, publicationClock })
637
637
  if (outcome.reason === "no_upstream") {
638
638
  if (await upstreamBack({ root, spawnGit, clock })) continue
639
639
  return { result: "skipped", reason: "upstream_gone" }
@@ -672,9 +672,11 @@ export async function runPushWorker(options) {
672
672
  const sleep = (options.clock ?? REAL_CLOCK).sleep
673
673
  for (let attempt = 0; ; attempt += 1) {
674
674
  const result = await pushRounds(options)
675
- // A network or contention failure may clear by itself: the worker waits (backing off, outside the lock) and tries again, so a save is never left waiting for the next write to retry it. Conflicts and auth failures need a person and are not retried.
676
- if (result?.result !== "blocked" || !RETRYABLE.has(result.reason) || attempt >= delays.length) return result
677
- await sleep(delays[attempt])
675
+ // Pending checks may outlive the network retry budget. Keep qualifying them without arming any merge trigger early.
676
+ if (result?.result !== "blocked") return result
677
+ const pending = result.reason === "publication_blocked" && readSyncStatus({ root: options.root, env: options.env })?.publication?.pending_checks === true
678
+ if (!pending && (!RETRYABLE.has(result.reason) || attempt >= delays.length)) return result
679
+ await sleep(delays[Math.min(attempt, delays.length - 1)] ?? 60_000)
678
680
  }
679
681
  }
680
682
 
@@ -694,7 +696,7 @@ async function pushRounds(options) {
694
696
 
695
697
  async function pushRound({
696
698
  root, env = process.env, debounceMs = DEFAULT_DEBOUNCE_MS, spawnGit = spawnSync, clock = REAL_CLOCK, fileProblem = queueDeskProblemFiling,
697
- stderr = process.stderr, quietMs, maxWaitMs,
699
+ stderr = process.stderr, quietMs, maxWaitMs, publicationClock,
698
700
  }) {
699
701
  const lock = await acquireSyncLock({ root, env })
700
702
  if (lock?.refused) {
@@ -716,7 +718,7 @@ async function pushRound({
716
718
  const logs = commitWaitingLogs(root, spawnGit)
717
719
  if (["committed", "empty"].includes(logs) && waitingLogs(root, spawnGit).length === 0) clearLogsPending({ root, env })
718
720
  if (!pushable) return { result: { result: "skipped" }, logs }
719
- return { result: await deliverUntilDone({ root, env, spawnGit, fileProblem, clock }), logs }
721
+ return { result: await deliverUntilDone({ root, env, spawnGit, fileProblem, clock, publicationClock }), logs }
720
722
  } finally {
721
723
  lock.release()
722
724
  }
@@ -5,12 +5,14 @@
5
5
  // logs and cards merge), a conflict in the content itself stays open and is named with its files, and every open desk/publish/*
6
6
  // PR of the repository that conflicts is found and settled even when this machine never recorded it.
7
7
 
8
+ import { spawnSync } from "node:child_process"
8
9
  import { readdirSync, readFileSync } from "node:fs"
9
10
  import * as path from "node:path"
10
11
 
11
12
  import { deliveryPaths, removeWorktree, replay, runner, upstreamOf } from "./deliver.js"
12
13
  import { resolveDeskStateDir } from "./last-start.js"
13
14
  import { publicationPolicy, publishPullRequest, repository } from "./pr-publication.js"
15
+ import { ghEnvFor } from "./remote-identity.js"
14
16
  import { readSyncStatus, updateSyncStatus } from "./sync-worker.js"
15
17
 
16
18
  const STUCK_AFTER_MS = 10 * 60 * 1000
@@ -83,7 +85,7 @@ const conflictFiles = (save) => save.conflict?.files ?? []
83
85
  /** One plain sentence per stuck save, naming its PR link, and the files that conflict when Desk could not merge them. */
84
86
  export const stuckLine = (save) => conflictFiles(save).length > 0
85
87
  ? `Desk save not on main after ${save.minutes} min: ${save.url} conflicts with main in ${conflictFiles(save).join(", ")}, which Desk cannot merge by itself; open the pull request, resolve the conflict and merge it`
86
- : `Desk save not on main after ${save.minutes} min: ${save.url} (the pull request is still open; Desk rebases it and the merge-when-green relay merges it once its checks are green)`
88
+ : `Desk save not on main after ${save.minutes} min: ${save.url} (the pull request is still open; Desk retries qualification and merges it or hands it to the merge-when-green relay only after its checks pass)`
87
89
 
88
90
  /** `reply` with the stuck saves named, when there are any. A reply that is not an object, or a call with no desk, is returned as it is. */
89
91
  export function withStuckSaves(reply, { root, env, now }) {
@@ -137,8 +139,20 @@ function supersession(git, head, main, link) {
137
139
 
138
140
  const short = (sha) => sha.slice(0, 12)
139
141
 
142
+ // The repository a gh command names: a pull request URL, or `--repo` as `<host>/<owner>/<name>`.
143
+ export function repositoryOf(args) {
144
+ const flag = args.indexOf("--repo")
145
+ const text = flag >= 0 ? args[flag + 1] : args.find((arg) => /^https:\/\/[^/]+\/[^/]+\/[^/]+\/pull\/\d+/u.test(arg))?.replace(/^https:\/\//u, "")
146
+ const [host, owner, repo] = typeof text === "string" ? text.split("/") : []
147
+ return host && owner && repo ? { host, owner, repo } : null
148
+ }
149
+
140
150
  function ghRun(spawnGit, root, args) {
141
- const result = spawnGit("gh", args, { cwd: root, encoding: "utf8", windowsHide: true, timeout: NETWORK_TIMEOUT_MS, env: process.env })
151
+ /* istanbul ignore next -- only the real spawnSync asks gh which account can reach the repository; tests inject a fake. */
152
+ const repo = spawnGit === spawnSync ? repositoryOf(args) : null
153
+ /* istanbul ignore next -- see above. */
154
+ const env = repo === null ? process.env : ghEnvFor({ ...repo, env: process.env, spawn: spawnSync })
155
+ const result = spawnGit("gh", args, { cwd: root, encoding: "utf8", windowsHide: true, timeout: NETWORK_TIMEOUT_MS, env })
142
156
  return { status: result.status, stdout: typeof result.stdout === "string" ? result.stdout : "" }
143
157
  }
144
158
 
@@ -216,7 +230,19 @@ function settle({ root, env, spawnGit, clock }) {
216
230
  else outcome.waiting.push(save.url)
217
231
  continue
218
232
  }
219
- if (view.mergeable !== "CONFLICTING") { outcome.waiting.push(save.url); continue }
233
+ if (view.mergeable !== "CONFLICTING") {
234
+ try {
235
+ const policy = publicationPolicy(git, main)
236
+ if (policy !== null) {
237
+ publishPullRequest({ git, spawnGit, root, upstream, head: save.head, onto: main, policy, clock, track: savesFor({ root, env, now: Date.now }) })
238
+ continue
239
+ }
240
+ } catch {
241
+ // Qualification still pending or refused: retain the receipt for the next settlement and status reply.
242
+ }
243
+ outcome.waiting.push(save.url)
244
+ continue
245
+ }
220
246
  const rebased = rebaseSave({ git, spawnGit, root, env, upstream, save, main, clock })
221
247
  if (rebased === "rebased") outcome.rebased.push(save.url)
222
248
  else outcome.waiting.push(save.url)
@@ -304,10 +304,11 @@ export async function callTool({ deskRoot, name, input, person = null, statusCon
304
304
  // `desk` points a card tool at another desk registered on this machine. That desk has its own search index and focus, so the call takes neither of this session's.
305
305
  if (SIBLING_DESK_TOOLS.includes(name) && target.input.desk !== undefined) {
306
306
  const { desk, ...rest } = target.input
307
- target = { deskRoot: resolveSiblingDesk({ tool: name, desk, boundRoot: deskRoot, person, env }).deskRoot, input: rest, statusContext: {}, search: null }
307
+ const sibling = await resolveSiblingDesk({ tool: name, desk, boundRoot: deskRoot, person, env })
308
+ target = { deskRoot: sibling.deskRoot, person: sibling.person, input: rest, statusContext: {}, search: null }
308
309
  }
309
310
  const invoke = () => impl({
310
- deskRoot: target.deskRoot, input: target.input, person, statusContext: target.statusContext, search: target.search,
311
+ deskRoot: target.deskRoot, input: target.input, person: target.person === undefined ? person : target.person, statusContext: target.statusContext, search: target.search,
311
312
  queryRouter: searchRouter(target.search), signal,
312
313
  })
313
314
  let stageStore = null
@@ -43,8 +43,6 @@ const HAND_WRITTEN_DESCRIPTIONS = {
43
43
  "Use when a task's work is finished or cancelled: move <track>/<slug>/ to <track>/_archive/<slug>/. A task not yet done or cancelled needs `evidence` or `outcome: \"cancelled\"`. Returns archive_pending with the retained path and next_action when publication is unproven; that is not completed publication. Repeating an archived task is safe.",
44
44
  task_signoff:
45
45
  "Record the operator's answer to a delivered task: accepted or refused. Call it only after the operator has answered, in a turn after the one that delivered the work. A refusal needs `reason` (theirs) and `return_reason` (your own reading) and puts the task back to processing. Desk records any call as the operator's answer without checking which agent made it, so it is the main agent's tool: a subagent has not heard the answer.",
46
- task_focus:
47
- "Declare the task this session is working on, so its time is credited to it. Pass `track` and `slug` of an existing card (live or archived), or `clear: true` for a side conversation. Main agent only; a subagent never calls it. Writes nothing. Returns `task_status`, `recent_progress`, `next_step`, any `shelved_lessons` to read before you act, and `archive_due` for a done/cancelled card. `task_create` with `focus: true` does the same for a new task.",
48
46
  track_create:
49
47
  "Use when new work needs its own track: create a track at <slug>/track.md. `slug` must be an outcome name (1-6 lowercase kebab-case words, at most 48 characters) and `scope` is required: one line, at most 240 characters, \"<what belongs>; not <what doesn't>\". A rejection says what to fix. On a Git desk it stages and commits the new track.md; a commit failure keeps the written file and is reported in a `commit` field.",
50
48
  track_update:
@@ -30,7 +30,7 @@ const TASK_TARGET = {
30
30
  slug: text("The task folder name."),
31
31
  }
32
32
 
33
- const SIBLING_DESK = text("Write the task in another desk registered on this machine instead of this session's desk: its name, repo or absolute folder as desk_status lists it under machine_desks. A desk that is not registered, or a Crew desk, is refused and nothing is written; the answer carries `desk_root`.")
33
+ const SIBLING_DESK = text("Write the task in another desk registered on this machine instead of this session's desk: its name, repo or absolute folder as desk_status lists it under machine_desks. A desk that is not registered is refused and nothing is written. In a Crew desk the card is written as the member this machine's GitHub sign-in resolves to on that desk's roster; no member means a refusal. The answer carries `desk_root`.")
34
34
 
35
35
  const DISPLAY_LABEL = text("Optional short description of the focused task, at most 72 characters; never paths, URLs, emails or credentials. Unsafe labels are ignored.")
36
36
 
@@ -117,6 +117,7 @@ const TASK_PROGRESS = {
117
117
  next_step: text("Replaces the card's `**Next step:**` paragraph."),
118
118
  }
119
119
 
120
+ const CHILD_SESSION = text("The session id of a child you delegated this work to, written as a `Child session:` line at the top of the `log` entry (pass `log` too), so a drain or coordinator can find who owns the work. Read your own child's id from the host that started it.")
120
121
  const TASK_LOG = text("A dated entry for the task's `log.md` beside its card, the place for rulings, decisions and where the evidence is. Cheap to repeat: entries written close together share one commit and one push, and a call never waits on a publication still running.")
121
122
 
122
123
  const REPLACE_SECTION = {
@@ -208,7 +209,7 @@ const HAND_WRITTEN_INPUT_SCHEMAS = Object.freeze({
208
209
  origin_note: text("When the agent started the task: one line on what it noticed."),
209
210
  steps: { type: "array", items: STEP, description: "The outcome's steps, in order, written as the card's `## Steps` table. A new step needs `id`, `repo` and `depends_on`." },
210
211
  }, ["track", "slug", "title"]),
211
- task_update: schema({ ...TASK_TARGET, status: text("Shorthand for `frontmatter.status`: one of drafting, processing, validating, collaborating, paused, blocked, done, cancelled. Moving to `done` needs `evidence`."), ...CARD_UPDATE, ...TASK_PROGRESS, evidence: TASK_DONE_EVIDENCE, repos_removed_reason: REPOS_REMOVED_REASON, return_reason: RETURN_REASON, step: STEP, resource: RESOURCE, resources: { type: "array", items: RESOURCE, description: "Several `resource` rows in one call, written and committed once, in order after `resource` when both are given; use it for a cleanup of many worktrees or branches. Any bad row refuses the whole call." }, desk: SIBLING_DESK, display_label: DISPLAY_LABEL, replace_section: REPLACE_SECTION, log: TASK_LOG, content_home: CONTENT_HOME, ...TASK_MOVE }, []),
212
+ task_update: schema({ ...TASK_TARGET, status: text("Shorthand for `frontmatter.status`: one of drafting, processing, validating, collaborating, paused, blocked, done, cancelled. Moving to `done` needs `evidence`."), ...CARD_UPDATE, ...TASK_PROGRESS, evidence: TASK_DONE_EVIDENCE, repos_removed_reason: REPOS_REMOVED_REASON, return_reason: RETURN_REASON, step: STEP, resource: RESOURCE, resources: { type: "array", items: RESOURCE, description: "Several `resource` rows in one call, written and committed once, in order after `resource` when both are given; use it for a cleanup of many worktrees or branches. Any bad row refuses the whole call." }, desk: SIBLING_DESK, display_label: DISPLAY_LABEL, replace_section: REPLACE_SECTION, log: TASK_LOG, child_session: CHILD_SESSION, content_home: CONTENT_HOME, ...TASK_MOVE }, []),
212
213
  task_archive: schema({ ...TASK_TARGET, desk: SIBLING_DESK, evidence: TASK_DONE_EVIDENCE, outcome: TASK_ARCHIVE_OUTCOME }, ["track", "slug"]),
213
214
  task_signoff: schema({
214
215
  desk: SIBLING_DESK,
@@ -219,12 +220,6 @@ const HAND_WRITTEN_INPUT_SCHEMAS = Object.freeze({
219
220
  reason: { type: "string", enum: ["not_what_was_asked", "defect", "changed_ask", "incomplete", "other"], description: "Required when refused, not allowed when accepted: the operator's reason, mapped from what they said." },
220
221
  return_reason: { ...RETURN_REASON, description: "Required when refused, not allowed when accepted: your own reading of the cause. agent_error is your mistake, changed_ask the operator's new ask, new_information something nobody knew, external an outside break." },
221
222
  }, ["track", "slug", "outcome"]),
222
- task_focus: schema({
223
- track: text("The track folder of the task you are working on; give it with `slug`."),
224
- slug: text("The task folder name; give it with `track`."),
225
- clear: flag("Pass true, alone, to declare no task: for a side conversation that belongs to none."),
226
- display_label: DISPLAY_LABEL,
227
- }),
228
223
  track_create: schema({
229
224
  slug: text("The track folder name: an outcome name, 1-6 lowercase kebab-case words, at most 48 characters."),
230
225
  title: text("The track title."),
@@ -4,6 +4,7 @@ import { promises as fs } from "node:fs"
4
4
  import * as path from "node:path"
5
5
  import { rewriteForMove } from "../util/archive-links.js"
6
6
  import { isGitRepository } from "../util/git-stage.js"
7
+ import { planCitationRewrites } from "../util/citations.js"
7
8
 
8
9
  const SKIP_DIRS = new Set(["node_modules", ".git", ".state", "_cache"])
9
10
  const posixPath = (file) => file.split(path.sep).join("/")
@@ -115,6 +116,8 @@ export async function planArchiveLinks({ effectiveRoot, srcDir, archiveDir, trac
115
116
  state.not_rewritten.push({ file: rel, reason: error.message })
116
117
  }
117
118
  }
119
+ for (const cited of await planCitationRewrites({ root: effectiveRoot, pairs: [[sourcePrefix, destinationPrefix]] }))
120
+ plan.inbound.push({ ...cited, unresolved: [] })
118
121
  const nextTrackPlan = trackText === null ? trackPlan
119
122
  : await composeTrackLinks({ plan, trackPlan, trackFile, trackRel, trackText, effectiveRoot, spawnGit })
120
123
  return { plan, state, trackPlan: nextTrackPlan }
@@ -342,14 +342,18 @@ async function saveDesk({ deskRoot, input, person = null, env = process.env, spa
342
342
  const everything = stagedChanges(deskRoot, [], spawnGit)
343
343
  if (everything === null) return { status: "nothing_to_commit", commit: notCommitted(deskRoot, paths, message, "git could not list the staged changes") }
344
344
  const listed = paths.map((p) => path.relative(deskRoot, path.resolve(deskRoot, p)).split(path.sep).join("/"))
345
- const covered = (p) => listed.some((rel) => rel === "" || p === rel || p.startsWith(`${rel}/`))
345
+ const covered = (p, rel) => rel === "" || p === rel || p.startsWith(`${rel}/`)
346
346
  for (const change of everything) {
347
- const missing = change.paths.filter((p) => !covered(p))
347
+ const missing = change.paths.filter((p) => !listed.some((rel) => covered(p, rel)))
348
348
  if (change.paths.length === 2 && missing.length === 1) {
349
349
  throw Object.assign(new Error(`desk_save: add ${missing[0]} to \`paths\`: a move is committed with both its old and its new path`), { code: "desk_save_a_move_is_committed_with_2" })
350
350
  }
351
351
  }
352
- const committed = commitPaths(deskRoot, paths, message, spawnGit, undefined, { keepLocal: true })
352
+ // A listed path with no change and no staged change (an ignored generated file, say) is not known to Git, and `git commit -- <it>`
353
+ // would refuse the whole commit with a pathspec error; it is left out and named in the answer.
354
+ const changed = paths.filter((p, i) => unstaged.includes(p) || everything.some((change) => change.paths.some((q) => covered(q, listed[i]))))
355
+ const unchanged = paths.filter((p) => !changed.includes(p))
356
+ const committed = commitPaths(deskRoot, changed, message, spawnGit, undefined, { keepLocal: true })
353
357
  if (!committed.ok) {
354
358
  return commitNotMade(commitFailure({ root: deskRoot, paths: listed, message, committed }))
355
359
  }
@@ -360,6 +364,7 @@ async function saveDesk({ deskRoot, input, person = null, env = process.env, spa
360
364
  const answer = published
361
365
  ? { status: "committed", desk_pushed: true, desk_note: "Desk published these files to the remote's default branch, so they are already on the remote. Run no git to push them." }
362
366
  : { status: "committed", ...deskPushNote({ root: deskRoot, spawnGit, note: DESK_SAVE_NOTE }), desk_pushed: false }
367
+ if (unchanged.length > 0) answer.unchanged_paths = unchanged
363
368
  if (committed.checkout !== undefined) {
364
369
  answer.checkout = committed.checkout
365
370
  answer.checkout_note = committed.checkout_note
@@ -4,9 +4,10 @@
4
4
  // repository, a plain rename otherwise), touch the small set of frontmatter
5
5
  // fields that record ownership (`track:` on a moved/reparented task card),
6
6
  // and best-effort keep each `track.md`'s "## Tasks" table in sync. Neither
7
- // tool ever rewrites free text elsewhere — it only reports, in `mentions`,
8
- // other text files under the desk that still mention the old relative path,
9
- // so the agent (or the operator) can fix them if they matter. On a Git desk
7
+ // tool rewrites free text elsewhere — they only report, in `mentions`,
8
+ // other Markdown files under the desk that still mention the old relative
9
+ // path. The one exception is a task move, which repoints whole-path
10
+ // citations in the JSON records under `_shared/` and `pages/`. On a Git desk
10
11
  // they stage every file they write (M4-5 fix round 4) and commit exactly
11
12
  // the paths they wrote — the moved directory plus any track.md tables it
12
13
  // edited — right after (M4-6 Part 2); a plain rename with no commit is as
@@ -31,6 +32,7 @@ import { commitFailure, withNext } from "../util/route-around.js"
31
32
  import { deskFailure } from "../runtime/desk-failure.js"
32
33
  import { schedulePush as schedulePushDefault } from "../runtime/sync-worker.js"
33
34
  import { redactCredentialLikeText, redactName } from "../util/redact.js"
35
+ import { planCitationRewrites } from "../util/citations.js"
34
36
  import { focusNote } from "./task-focus.js"
35
37
  import { resolveTaskHandle, resolveTrackHandle } from "../desk/handles.js"
36
38
  import {
@@ -399,6 +401,27 @@ async function findMentions({ root, oldRelPath, exclude }) {
399
401
  return mentions.map((abs) => relPath(root, abs))
400
402
  }
401
403
 
404
+ // ── Citations in shared JSON records ───────────────────────────────────────
405
+
406
+ /**
407
+ * Repoints citations of a moved folder (and, for a merge, its renamed card) in the JSON records under `_shared/` and `pages/`, so the
408
+ * workspace's own record checks keep passing. A record with unstaged work on a Git desk is left alone and named. Returns
409
+ * `{ files, left }`: absolute paths written, and `[{ file, reason }]`.
410
+ */
411
+ async function repointCitations({ root, pairs, spawnGit }) {
412
+ const files = [], left = []
413
+ const git = isGitRepository(root, spawnGit)
414
+ for (const cited of await planCitationRewrites({ root, pairs })) {
415
+ if (git && hasUnstagedWork(root, [cited.rel], spawnGit)) {
416
+ left.push({ file: cited.rel, reason: "it has unstaged or untracked changes, so another session may be editing it" })
417
+ continue
418
+ }
419
+ await fs.writeFile(cited.file, cited.after)
420
+ files.push(cited.file)
421
+ }
422
+ return { files, left }
423
+ }
424
+
402
425
  // ── task_update ────────────────────────────────────────────────────────────
403
426
 
404
427
  /**
@@ -651,6 +674,11 @@ export async function moveTask({ deskRoot, input, person = null, search, statusC
651
674
  }
652
675
  }
653
676
 
677
+ const pairs = intoTask === undefined ? [] : [[`${relPath(effectiveRoot, srcDir)}/task.md`, relPath(effectiveRoot, destFile)]]
678
+ pairs.push([relPath(effectiveRoot, srcDir), relPath(effectiveRoot, destDir)])
679
+ const cited = await repointCitations({ root: effectiveRoot, pairs, spawnGit })
680
+ for (const file of cited.files) updatedFiles.push(relPath(deskRoot, file))
681
+
654
682
  const writtenFiles = updatedFiles.map((p) => path.join(deskRoot, p))
655
683
  stageWrites({
656
684
  root: effectiveRoot,
@@ -681,6 +709,7 @@ export async function moveTask({ deskRoot, input, person = null, search, statusC
681
709
  updated_files: updatedFiles.map(shownPath),
682
710
  mentions: mentions.map(shownPath),
683
711
  }
712
+ if (cited.left.length > 0) result.citations_not_repointed = cited.left.map((entry) => ({ ...entry, file: shownPath(entry.file) }))
684
713
  if (commit) result.commit = commit
685
714
  // The held focus follows the card it names (a merge follows into the card that keeps the job); with nothing
686
715
  // focused, a task tool call carries the no-focus hint until the session declares. A different focus is left alone.
@@ -3,6 +3,7 @@
3
3
 
4
4
  import { realpathSync } from "node:fs"
5
5
  import * as path from "node:path"
6
+ import { memberMessage, resolveMember } from "../desk/crew-member.js"
6
7
  import { readMachineDesks, resolveMachineDesk } from "../desk/machine-desks.js"
7
8
 
8
9
  export const SIBLING_DESK_TOOLS = Object.freeze(["task_create", "task_update", "task_archive", "task_signoff"])
@@ -24,14 +25,19 @@ function refusal(tool, problem) {
24
25
  * A name, repo or owner resolves as in desk_status; an absolute path must be a registered desk's folder.
25
26
  */
26
27
  // Only the operator-controlled registry counts (`DESK_REGISTRY` or the recorded registry path): the bound desk's own `_meta/desks.md` is writable by this session, so it cannot widen where the session writes.
27
- export function resolveSiblingDesk({ tool, desk, boundRoot, person, env }) {
28
+ export async function resolveSiblingDesk({ tool, desk, boundRoot, person, env }) {
28
29
  if (typeof desk !== "string" || desk.trim() === "") throw refusal(tool, "`desk` must be a non-empty string.")
29
- if (person) throw refusal(tool, "this session writes as a person-scoped member, and another desk's card is written under that desk's own authority: open a session in that desk.")
30
30
  const machine = readMachineDesks({ homeDir: env.HOME, root: null, env })
31
31
  const wanted = desk.trim()
32
32
  const byPath = path.isAbsolute(wanted) ? machine.filter((candidate) => real(candidate.path) === real(wanted)) : []
33
33
  const found = byPath.length === 1 ? (byPath[0].present ? { desk: byPath[0] } : { problem: `The ${byPath[0].name} desk is registered at ${byPath[0].path} but is not on this machine.` }) : resolveMachineDesk(wanted, machine)
34
34
  if (found.desk === undefined) throw refusal(tool, `${found.problem}`)
35
- if (found.desk.kind === "crew") throw refusal(tool, `${found.desk.name} is a Crew desk, where cards are written under a member's authority: open a session in that desk.`)
36
- return { deskRoot: real(found.desk.path) }
35
+ if (found.desk.kind === "crew") {
36
+ // The write is made as the member this machine's GitHub sign-in is on that desk's roster, the same way a session opened there would resolve it.
37
+ const member = await resolveMember({ deskRoot: found.desk.path, env })
38
+ if (member.person === null) throw refusal(tool, `${found.desk.name} is a Crew desk, and this machine's GitHub sign-in is not a member on its roster (${memberMessage(member)}). Sign in to gh as the account you joined with, or open a session in that desk.`)
39
+ return { deskRoot: real(found.desk.path), person: member.person }
40
+ }
41
+ if (person) throw refusal(tool, "this session writes as a person-scoped member, and a solo desk's card is written by a session opened in that desk.")
42
+ return { deskRoot: real(found.desk.path), person: null }
37
43
  }