@chroxy/server 0.10.0
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.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control Room — Integrations survey (#5499, epic #5498).
|
|
3
|
+
*
|
|
4
|
+
* Sibling to the host survey (survey.js) and the runner survey (runners.js).
|
|
5
|
+
* Where those classify git repos and self-hosted runners, this one surveys
|
|
6
|
+
* **integration status** per repo — repo-memory (#5499) and repo-relay
|
|
7
|
+
* (#5501):
|
|
8
|
+
*
|
|
9
|
+
* - config: does `.repo-memory.json` exist in the repo root? Parse its
|
|
10
|
+
* `summarizer` and enabled tool groups when it does.
|
|
11
|
+
* - cache: `.repo-memory/cache.db` (+ `-wal` sidecar) file stats — present,
|
|
12
|
+
* combined size, newest mtime (the "last activity" proxy, since the
|
|
13
|
+
* telemetry report carries no timestamp of its own).
|
|
14
|
+
* - report: `repo-memory report <repoRoot> --json --diagnostics` — total
|
|
15
|
+
* events, hit ratio, tokens saved, cache entry/stale counts. Read-only CLI.
|
|
16
|
+
* - relay (#5501): `.github/workflows/repo-relay.yml` presence, the
|
|
17
|
+
* `uses: blamechris/repo-relay@<ref>` version pin (tag or sha+comment),
|
|
18
|
+
* the latest upstream release (`gh api .../releases/latest`, ONE call per
|
|
19
|
+
* snapshot + a short module cache), and the five most recent workflow runs
|
|
20
|
+
* (`gh run list -R <owner>/<repo>` — owner/repo derived from the git
|
|
21
|
+
* remote via survey.js's parseGithubOwnerRepo).
|
|
22
|
+
*
|
|
23
|
+
* Degradation semantics (the survey NEVER fails because one cell did):
|
|
24
|
+
* - The `repo-memory` binary is resolved ONCE per snapshot (`which`), not per
|
|
25
|
+
* repo. When absent, every configured repo's report cell degrades with a
|
|
26
|
+
* per-repo `reason` and the snapshot carries a `repoMemoryCli` note.
|
|
27
|
+
* - Same for `gh` (#5501): one probe per snapshot; when absent every
|
|
28
|
+
* installed repo's relay run/release cells degrade with a per-repo
|
|
29
|
+
* `reason` and the snapshot carries a `ghCli` note.
|
|
30
|
+
* - A per-repo CLI failure (exit 1, timeout, unparseable output) degrades
|
|
31
|
+
* that repo's report cell with a `reason` string.
|
|
32
|
+
* - A repo without `.repo-memory.json` is a quiet `configured: false` row —
|
|
33
|
+
* absence is signal, not an error. Same for a repo without the relay
|
|
34
|
+
* workflow file (`installed: false`).
|
|
35
|
+
* - A repo with no GitHub remote still answers `installed` (and the pin)
|
|
36
|
+
* from the filesystem; the run cells degrade with reason
|
|
37
|
+
* 'no GitHub remote'. Drift is still assessed — the pin comes from the
|
|
38
|
+
* workflow file and the latest release is repo-independent.
|
|
39
|
+
*
|
|
40
|
+
* The result conforms to `ServerIntegrationStatusSnapshotSchema` from
|
|
41
|
+
* `@chroxy/protocol` (minus the `type` field, which the WS handler adds).
|
|
42
|
+
*
|
|
43
|
+
* Every external interaction is injectable so tests never touch real fs/exec:
|
|
44
|
+
* - `_readFile(path, enc)` — async, resolves a string (rejects when absent).
|
|
45
|
+
* - `_stat(path)` — async, resolves `{ size, mtimeMs }` (rejects when absent).
|
|
46
|
+
* - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`
|
|
47
|
+
* (the promisified `child_process.execFile` shape). Rejections tolerated.
|
|
48
|
+
* - `_now()` — returns a `Date` (defaults to `new Date()`).
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
import { execFile } from 'child_process'
|
|
52
|
+
import { promisify } from 'util'
|
|
53
|
+
import { readFile, stat } from 'fs/promises'
|
|
54
|
+
import { join } from 'path'
|
|
55
|
+
import { parseGithubOwnerRepo } from './survey.js'
|
|
56
|
+
import { DEFAULT_CONCURRENCY, EXEC_TIMEOUT_MS } from './constants.js'
|
|
57
|
+
|
|
58
|
+
const execFileAsync = promisify(execFile)
|
|
59
|
+
|
|
60
|
+
/** Output cap for the report subprocess (report JSON is small). */
|
|
61
|
+
const EXEC_MAX_BUFFER = 8 * 1024 * 1024
|
|
62
|
+
/** Shared exec options for every probe. */
|
|
63
|
+
const EXEC_OPTS = { timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
|
|
64
|
+
|
|
65
|
+
/** Snapshot-level note used when the binary probe finds nothing. */
|
|
66
|
+
export const CLI_MISSING_NOTE = 'repo-memory CLI not found on PATH — install @blamechris/repo-memory globally or set controlRoomRepoMemoryBin'
|
|
67
|
+
|
|
68
|
+
/** #5501: snapshot-level note (and per-repo reason) when `gh` is missing. */
|
|
69
|
+
export const GH_MISSING_NOTE = 'gh CLI not found on PATH — install GitHub CLI (gh) to populate repo-relay run and release data'
|
|
70
|
+
|
|
71
|
+
/** #5501: per-repo reason when a repo has no recognisable GitHub remote. */
|
|
72
|
+
export const NO_GITHUB_REMOTE_REASON = 'no GitHub remote'
|
|
73
|
+
|
|
74
|
+
/** #5501: the upstream action repo whose releases define "latest". */
|
|
75
|
+
export const RELAY_UPSTREAM_REPO = 'blamechris/repo-relay'
|
|
76
|
+
|
|
77
|
+
/** #5501: the workflow file (and `gh run list --workflow` target) per repo. */
|
|
78
|
+
export const RELAY_WORKFLOW_FILE = 'repo-relay.yml'
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* #5500: timeout for `repo-memory index` — deliberately much more generous
|
|
82
|
+
* than the 20s survey probes: a cold index of a big repo summarizes every
|
|
83
|
+
* indexable file and legitimately takes minutes-of-seconds. A run that blows
|
|
84
|
+
* through this is treated as a failure with a reason, never a hang.
|
|
85
|
+
*/
|
|
86
|
+
export const INDEX_TIMEOUT_MS = 120000
|
|
87
|
+
/** Output cap for the index subprocess (per-file report lines can add up). */
|
|
88
|
+
const INDEX_EXEC_OPTS = { timeout: INDEX_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Parse a repo's `.repo-memory.json` config.
|
|
92
|
+
*
|
|
93
|
+
* @param {string|null} text - raw config contents, or null when absent.
|
|
94
|
+
* @returns {{ summarizer: string|null, toolGroups: string[] }|null} parsed
|
|
95
|
+
* config, or null when the file is absent / unparseable / not an object.
|
|
96
|
+
* `toolGroups` lists the tool groups enabled under the `tools` map (keys
|
|
97
|
+
* with a truthy value), sorted for stable output.
|
|
98
|
+
*/
|
|
99
|
+
export function parseRepoMemoryConfig(text) {
|
|
100
|
+
if (text === null || text === undefined) return null
|
|
101
|
+
let parsed
|
|
102
|
+
try {
|
|
103
|
+
parsed = JSON.parse(String(text).replace(/^/, ''))
|
|
104
|
+
} catch {
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
|
|
108
|
+
const summarizer = typeof parsed.summarizer === 'string' && parsed.summarizer.length > 0 ? parsed.summarizer : null
|
|
109
|
+
const toolGroups = []
|
|
110
|
+
if (parsed.tools && typeof parsed.tools === 'object' && !Array.isArray(parsed.tools)) {
|
|
111
|
+
for (const [group, enabled] of Object.entries(parsed.tools)) {
|
|
112
|
+
if (enabled) toolGroups.push(group)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
toolGroups.sort()
|
|
116
|
+
return { summarizer, toolGroups }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Coerce a tolerated "last activity" hint off the report into an ISO-8601
|
|
121
|
+
* string. Current CLI versions (verified against 0.15.0) carry no timestamp —
|
|
122
|
+
* this only fires if a future version adds `lastEventAt` / `lastActivityAt` /
|
|
123
|
+
* `lastActivity` as epoch-ms or an ISO string.
|
|
124
|
+
*
|
|
125
|
+
* @param {object} parsed - the parsed report JSON.
|
|
126
|
+
* @returns {string|null}
|
|
127
|
+
*/
|
|
128
|
+
function deriveLastActivity(parsed) {
|
|
129
|
+
const raw = parsed.lastEventAt ?? parsed.lastActivityAt ?? parsed.lastActivity
|
|
130
|
+
if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
|
|
131
|
+
try {
|
|
132
|
+
return new Date(raw).toISOString()
|
|
133
|
+
} catch {
|
|
134
|
+
return null
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
138
|
+
const ms = Date.parse(raw)
|
|
139
|
+
if (!Number.isNaN(ms)) return new Date(ms).toISOString()
|
|
140
|
+
}
|
|
141
|
+
return null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Clamp a value to a non-negative finite number, else the fallback. */
|
|
145
|
+
function nonNegNumber(value, fallback) {
|
|
146
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Parse `repo-memory report --json --diagnostics` output into the
|
|
151
|
+
* `RepoMemoryReportSchema` shape. Tolerant: missing numeric fields default to
|
|
152
|
+
* 0, a missing `diagnostics` block leaves the entry counts null, the hit
|
|
153
|
+
* ratio is clamped to [0, 1]. Returns null only when the payload is
|
|
154
|
+
* unparseable or not an object.
|
|
155
|
+
*
|
|
156
|
+
* @param {string|null} json - raw stdout from the report command.
|
|
157
|
+
* @returns {object|null} a `RepoMemoryReportSchema`-shaped object, or null.
|
|
158
|
+
*/
|
|
159
|
+
export function parseRepoMemoryReport(json) {
|
|
160
|
+
if (json === null || json === undefined) return null
|
|
161
|
+
let parsed
|
|
162
|
+
try {
|
|
163
|
+
parsed = JSON.parse(String(json))
|
|
164
|
+
} catch {
|
|
165
|
+
return null
|
|
166
|
+
}
|
|
167
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
|
|
168
|
+
const diag = parsed.diagnostics && typeof parsed.diagnostics === 'object' ? parsed.diagnostics : null
|
|
169
|
+
const ratioRaw = nonNegNumber(parsed.cacheHitRatio, 0)
|
|
170
|
+
return {
|
|
171
|
+
totalEvents: Math.trunc(nonNegNumber(parsed.totalEvents, 0)),
|
|
172
|
+
cacheHits: Math.trunc(nonNegNumber(parsed.cacheHits, 0)),
|
|
173
|
+
cacheMisses: Math.trunc(nonNegNumber(parsed.cacheMisses, 0)),
|
|
174
|
+
cacheHitRatio: Math.min(1, ratioRaw),
|
|
175
|
+
estimatedTokensSaved: nonNegNumber(parsed.estimatedTokensSaved, 0),
|
|
176
|
+
cacheEntryCount: diag && Number.isFinite(diag.cacheEntryCount) && diag.cacheEntryCount >= 0
|
|
177
|
+
? Math.trunc(diag.cacheEntryCount)
|
|
178
|
+
: null,
|
|
179
|
+
staleEntryCount: diag && Number.isFinite(diag.staleEntryCount) && diag.staleEntryCount >= 0
|
|
180
|
+
? Math.trunc(diag.staleEntryCount)
|
|
181
|
+
: null,
|
|
182
|
+
lastActivity: deriveLastActivity(parsed),
|
|
183
|
+
// #5681 — failed search_by_purpose queries (repo-memory 0.17.0+). Absent on
|
|
184
|
+
// older CLIs; malformed entries tolerated: default to [] and keep only
|
|
185
|
+
// well-formed {query:string, count:>=0} pairs (mirrors the diagnostics guard).
|
|
186
|
+
topMissedQueries: Array.isArray(parsed.topMissedQueries)
|
|
187
|
+
? parsed.topMissedQueries
|
|
188
|
+
.filter(m => m && typeof m === 'object' && typeof m.query === 'string' && Number.isFinite(m.count) && m.count >= 0)
|
|
189
|
+
.map(m => ({ query: m.query, count: Math.trunc(m.count) }))
|
|
190
|
+
: [],
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Resolve the `repo-memory` binary ONCE per snapshot. An explicit override
|
|
196
|
+
* (config `controlRoomRepoMemoryBin`) wins without probing; otherwise probe
|
|
197
|
+
* the PATH with `which`. Any failure resolves null — the survey then degrades
|
|
198
|
+
* every CLI-derived cell with a snapshot-level note rather than spawning
|
|
199
|
+
* (and failing) once per repo.
|
|
200
|
+
*
|
|
201
|
+
* @param {Function} execFn - promisified execFile seam.
|
|
202
|
+
* @param {string} [binOverride] - explicit binary path from config.
|
|
203
|
+
* @returns {Promise<string|null>} resolved binary path, or null.
|
|
204
|
+
*/
|
|
205
|
+
export async function resolveRepoMemoryBin(execFn, binOverride) {
|
|
206
|
+
if (typeof binOverride === 'string' && binOverride.length > 0) return binOverride
|
|
207
|
+
return probeBinOnPath(execFn, 'repo-memory')
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Probe the PATH for a binary with `which`. Any failure resolves null.
|
|
212
|
+
*
|
|
213
|
+
* @param {Function} execFn - promisified execFile seam.
|
|
214
|
+
* @param {string} name - binary name (e.g. 'repo-memory', 'gh').
|
|
215
|
+
* @returns {Promise<string|null>} resolved binary path, or null.
|
|
216
|
+
*/
|
|
217
|
+
async function probeBinOnPath(execFn, name) {
|
|
218
|
+
try {
|
|
219
|
+
const { stdout } = await execFn('which', [name], EXEC_OPTS)
|
|
220
|
+
const path = String(stdout == null ? '' : stdout).split('\n')[0].trim()
|
|
221
|
+
return path.length > 0 ? path : null
|
|
222
|
+
} catch {
|
|
223
|
+
return null
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Stat the repo's cache db + wal sidecar into a `RepoMemoryCacheSchema` shape.
|
|
229
|
+
*
|
|
230
|
+
* @param {Function} statFn - async stat seam ({ size, mtimeMs }).
|
|
231
|
+
* @param {string} repoPath
|
|
232
|
+
* @returns {Promise<{ present: boolean, sizeBytes: number, lastModified: string|null }>}
|
|
233
|
+
*/
|
|
234
|
+
async function surveyCache(statFn, repoPath) {
|
|
235
|
+
const dbPath = join(repoPath, '.repo-memory', 'cache.db')
|
|
236
|
+
let db = null
|
|
237
|
+
try {
|
|
238
|
+
db = await statFn(dbPath)
|
|
239
|
+
} catch {
|
|
240
|
+
return { present: false, sizeBytes: 0, lastModified: null }
|
|
241
|
+
}
|
|
242
|
+
let wal = null
|
|
243
|
+
try {
|
|
244
|
+
wal = await statFn(`${dbPath}-wal`)
|
|
245
|
+
} catch {
|
|
246
|
+
wal = null
|
|
247
|
+
}
|
|
248
|
+
const sizeBytes = Math.max(0, Math.trunc(nonNegNumber(db?.size, 0) + nonNegNumber(wal?.size, 0)))
|
|
249
|
+
const mtimes = [db?.mtimeMs, wal?.mtimeMs].filter(m => typeof m === 'number' && Number.isFinite(m) && m > 0)
|
|
250
|
+
const lastModified = mtimes.length > 0 ? new Date(Math.max(...mtimes)).toISOString() : null
|
|
251
|
+
return { present: true, sizeBytes, lastModified }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* First meaningful line of a subprocess failure, for the per-repo `reason` /
|
|
256
|
+
* the reindex error message. `label` names the failing command ("repo-memory
|
|
257
|
+
* report" for the survey cell, "repo-memory index" for the #5500 action).
|
|
258
|
+
*
|
|
259
|
+
* @param {unknown} err
|
|
260
|
+
* @param {string} [label]
|
|
261
|
+
* @returns {string}
|
|
262
|
+
*/
|
|
263
|
+
function execFailureReason(err, label = 'repo-memory report') {
|
|
264
|
+
const stderr = err && typeof err === 'object' && typeof err.stderr === 'string' ? err.stderr : ''
|
|
265
|
+
const firstLine = stderr.split('\n').map(l => l.trim()).find(l => l.length > 0)
|
|
266
|
+
if (firstLine) return `${label} failed: ${firstLine}`
|
|
267
|
+
const message = err && typeof err === 'object' && typeof err.message === 'string' ? err.message : 'unknown error'
|
|
268
|
+
return `${label} failed: ${message}`
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* #5500: parse the human-readable `repo-memory index <root>` report into the
|
|
273
|
+
* `IntegrationActionCountsSchema` shape. The CLI has no `--json` for index —
|
|
274
|
+
* the report is line-based (verified empirically against the installed CLI):
|
|
275
|
+
*
|
|
276
|
+
* Indexed <root>
|
|
277
|
+
* scanned: 412
|
|
278
|
+
* summarized: 12
|
|
279
|
+
* already fresh: 398
|
|
280
|
+
* skipped: 2
|
|
281
|
+
* ...
|
|
282
|
+
*
|
|
283
|
+
* All four counts must parse or the whole result is null — the ack then
|
|
284
|
+
* carries `counts: null` and the dashboard falls back to a survey refresh
|
|
285
|
+
* rather than rendering a half-true breakdown.
|
|
286
|
+
*
|
|
287
|
+
* @param {string|null|undefined} stdout - raw stdout from the index command.
|
|
288
|
+
* @returns {{ scanned: number, summarized: number, fresh: number, skipped: number }|null}
|
|
289
|
+
*/
|
|
290
|
+
export function parseRepoMemoryIndexCounts(stdout) {
|
|
291
|
+
if (typeof stdout !== 'string' || stdout.length === 0) return null
|
|
292
|
+
const grab = re => {
|
|
293
|
+
const m = re.exec(stdout)
|
|
294
|
+
return m ? Number.parseInt(m[1], 10) : null
|
|
295
|
+
}
|
|
296
|
+
const counts = {
|
|
297
|
+
scanned: grab(/^\s*scanned:\s*(\d+)\s*$/m),
|
|
298
|
+
summarized: grab(/^\s*summarized:\s*(\d+)\s*$/m),
|
|
299
|
+
fresh: grab(/^\s*already fresh:\s*(\d+)\s*$/m),
|
|
300
|
+
skipped: grab(/^\s*skipped:\s*(\d+)\s*$/m),
|
|
301
|
+
}
|
|
302
|
+
for (const value of Object.values(counts)) {
|
|
303
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return null
|
|
304
|
+
}
|
|
305
|
+
return counts
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* #5500: run `repo-memory index <repoPath>` to prewarm/refresh the summary
|
|
310
|
+
* cache. Shares the survey's binary resolution (`resolveRepoMemoryBin`) so a
|
|
311
|
+
* `controlRoomRepoMemoryBin` override behaves identically for both surfaces.
|
|
312
|
+
* Deliberately NOT `--quiet` — the human-readable report is the only place
|
|
313
|
+
* the scanned/summarized/fresh/skipped counts exist.
|
|
314
|
+
*
|
|
315
|
+
* Resolves `{ counts }` (null when the report is unparseable). Throws with a
|
|
316
|
+
* legible message when the binary is missing or the run fails/times out —
|
|
317
|
+
* the WS handler turns that into an INTEGRATION_ACTION_FAILED session_error.
|
|
318
|
+
*
|
|
319
|
+
* @param {string} repoPath - canonical repo root (the handler validates
|
|
320
|
+
* membership in the surveyed repo set BEFORE calling this).
|
|
321
|
+
* @param {object} [opts]
|
|
322
|
+
* @param {string} [opts.bin] - explicit repo-memory binary path (skips probing).
|
|
323
|
+
* @param {Function} [opts._execFile] - promisified execFile seam.
|
|
324
|
+
* @returns {Promise<{ counts: object|null }>}
|
|
325
|
+
*/
|
|
326
|
+
export async function runRepoMemoryIndex(repoPath, opts = {}) {
|
|
327
|
+
const { bin, _execFile = execFileAsync } = opts
|
|
328
|
+
const binPath = await resolveRepoMemoryBin(_execFile, bin)
|
|
329
|
+
if (!binPath) throw new Error(CLI_MISSING_NOTE)
|
|
330
|
+
let stdout
|
|
331
|
+
try {
|
|
332
|
+
;({ stdout } = await _execFile(binPath, ['index', repoPath], INDEX_EXEC_OPTS))
|
|
333
|
+
} catch (err) {
|
|
334
|
+
throw new Error(execFailureReason(err, 'repo-memory index'))
|
|
335
|
+
}
|
|
336
|
+
return { counts: parseRepoMemoryIndexCounts(typeof stdout === 'string' ? stdout : '') }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
340
|
+
// #5502 — repo-relay Re-run action.
|
|
341
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* #5502: timeout for `gh run rerun` — a single API mutation, so it gets a
|
|
345
|
+
* 30s bound (longer than the 20s survey probes to ride out a slow API,
|
|
346
|
+
* nowhere near the 120s index budget).
|
|
347
|
+
*/
|
|
348
|
+
export const RERUN_TIMEOUT_MS = 30000
|
|
349
|
+
/** Shared exec options for the rerun mutation. */
|
|
350
|
+
const RERUN_EXEC_OPTS = { timeout: RERUN_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* #5502: build an Error carrying a stable machine `reason` alongside the
|
|
354
|
+
* human message. The WS handler echoes `reason` on the
|
|
355
|
+
* INTEGRATION_ACTION_FAILED session_error so the dashboard can branch
|
|
356
|
+
* without parsing message text.
|
|
357
|
+
*/
|
|
358
|
+
function rerunFailure(reason, message) {
|
|
359
|
+
const err = new Error(message)
|
|
360
|
+
err.reason = reason
|
|
361
|
+
return err
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* #5502: re-run a FAILED repo-relay workflow run via
|
|
366
|
+
* `gh run rerun <databaseId> -R <owner>/<repo>`.
|
|
367
|
+
*
|
|
368
|
+
* SECURITY — the client-supplied `runId` is a LOOKUP KEY, never a trusted
|
|
369
|
+
* exec target: before any mutation this re-fetches the same five-run window
|
|
370
|
+
* the observability snapshot (#5501) surfaced and requires the id to (a) be
|
|
371
|
+
* present in that fresh list and (b) have concluded `failure`. A stale,
|
|
372
|
+
* fabricated, or non-failed id is rejected with a legible reason — `gh run
|
|
373
|
+
* rerun` never sees an id the server didn't just observe. The owner/repo
|
|
374
|
+
* target likewise derives server-side from the repo's git remote (the same
|
|
375
|
+
* parseGithubOwnerRepo derivation the survey uses), never from the client.
|
|
376
|
+
*
|
|
377
|
+
* Throws with a machine `reason` (`gh-missing` / `no-github-remote` /
|
|
378
|
+
* `run-list-failed` / `unknown-run` / `run-not-failed` / `rerun-failed`) —
|
|
379
|
+
* the WS handler turns that into an INTEGRATION_ACTION_FAILED session_error.
|
|
380
|
+
*
|
|
381
|
+
* @param {string} repoPath - canonical repo root (the handler validates
|
|
382
|
+
* membership in the surveyed repo set BEFORE calling this).
|
|
383
|
+
* @param {number} runId - the GitHub Actions run databaseId to re-run.
|
|
384
|
+
* @param {object} [opts]
|
|
385
|
+
* @param {Function} [opts._execFile] - promisified execFile seam.
|
|
386
|
+
* @returns {Promise<{ runId: number }>}
|
|
387
|
+
*/
|
|
388
|
+
export async function runRepoRelayRerun(repoPath, runId, opts = {}) {
|
|
389
|
+
const { _execFile = execFileAsync } = opts
|
|
390
|
+
|
|
391
|
+
const ghPath = await probeBinOnPath(_execFile, 'gh')
|
|
392
|
+
if (!ghPath) throw rerunFailure('gh-missing', GH_MISSING_NOTE)
|
|
393
|
+
|
|
394
|
+
// Server-side owner/repo derivation — same source as the survey (#5501).
|
|
395
|
+
let target = null
|
|
396
|
+
try {
|
|
397
|
+
const { stdout } = await _execFile('git', ['remote', 'get-url', 'origin'], { ...EXEC_OPTS, cwd: repoPath })
|
|
398
|
+
target = parseGithubOwnerRepo(typeof stdout === 'string' ? stdout : '')
|
|
399
|
+
} catch {
|
|
400
|
+
target = null
|
|
401
|
+
}
|
|
402
|
+
if (!target) {
|
|
403
|
+
throw rerunFailure('no-github-remote', `cannot re-run: ${NO_GITHUB_REMOTE_REASON} for ${repoPath}`)
|
|
404
|
+
}
|
|
405
|
+
const slug = `${target.owner}/${target.repo}`
|
|
406
|
+
|
|
407
|
+
// runId re-validation: fresh fetch of the window the snapshot showed.
|
|
408
|
+
let listStdout
|
|
409
|
+
try {
|
|
410
|
+
;({ stdout: listStdout } = await _execFile(ghPath, [
|
|
411
|
+
'run', 'list', `--workflow=${RELAY_WORKFLOW_FILE}`, '-R', slug,
|
|
412
|
+
'--limit', '5', '--json', 'databaseId,conclusion,status',
|
|
413
|
+
], EXEC_OPTS))
|
|
414
|
+
} catch (err) {
|
|
415
|
+
throw rerunFailure('run-list-failed', execFailureReason(err, 'gh run list'))
|
|
416
|
+
}
|
|
417
|
+
const runs = parseRelayRuns(typeof listStdout === 'string' ? listStdout : '')
|
|
418
|
+
if (runs === null) {
|
|
419
|
+
throw rerunFailure('run-list-failed', 'gh run list produced unparseable output')
|
|
420
|
+
}
|
|
421
|
+
const match = runs.find(r => r.databaseId === runId)
|
|
422
|
+
if (!match) {
|
|
423
|
+
throw rerunFailure('unknown-run',
|
|
424
|
+
`runId ${runId} is not among the last 5 repo-relay runs for ${slug} — refresh the survey and retry`)
|
|
425
|
+
}
|
|
426
|
+
if (match.conclusion !== 'failure') {
|
|
427
|
+
const state = match.conclusion ?? match.status ?? 'not concluded'
|
|
428
|
+
throw rerunFailure('run-not-failed',
|
|
429
|
+
`run ${runId} did not fail (${state}) — only failed runs can be re-run`)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
try {
|
|
433
|
+
await _execFile(ghPath, ['run', 'rerun', String(runId), '-R', slug], RERUN_EXEC_OPTS)
|
|
434
|
+
} catch (err) {
|
|
435
|
+
throw rerunFailure('rerun-failed', execFailureReason(err, 'gh run rerun'))
|
|
436
|
+
}
|
|
437
|
+
return { runId }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
441
|
+
// #5501 — repo-relay observability helpers.
|
|
442
|
+
// ───────────────────────────────────────────────────────────────────────────
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Parse the `uses: blamechris/repo-relay@<ref>` line out of a workflow file.
|
|
446
|
+
*
|
|
447
|
+
* Handles both pin forms:
|
|
448
|
+
* - tag-pinned: `uses: blamechris/repo-relay@v1.1.0`
|
|
449
|
+
* - sha-pinned+comment: `uses: blamechris/repo-relay@f08840b9… # v1.1.0`
|
|
450
|
+
* (chroxy's own `.github/workflows/repo-relay.yml` is the live example)
|
|
451
|
+
*
|
|
452
|
+
* `version` resolves from the tag (when it looks like a version) or from the
|
|
453
|
+
* sha pin's trailing `# vX.Y.Z` comment; it stays null for a bare sha or a
|
|
454
|
+
* branch pin — drift then can't be assessed (`driftUnknown` upstream).
|
|
455
|
+
*
|
|
456
|
+
* @param {string|null|undefined} text - raw workflow YAML.
|
|
457
|
+
* @returns {{ ref: string, sha: string|null, version: string|null }|null}
|
|
458
|
+
* the parsed pin, or null when no repo-relay uses line is present.
|
|
459
|
+
*/
|
|
460
|
+
export function parseRelayPin(text) {
|
|
461
|
+
if (typeof text !== 'string' || text.length === 0) return null
|
|
462
|
+
const m = /^\s*(?:-\s+)?uses:\s*['"]?blamechris\/repo-relay@([^\s'"#]+)['"]?[ \t]*(?:#[ \t]*(\S+))?[ \t]*$/m.exec(text)
|
|
463
|
+
if (!m) return null
|
|
464
|
+
const ref = m[1]
|
|
465
|
+
const comment = m[2] || null
|
|
466
|
+
const versionLike = v => typeof v === 'string' && /^v?\d+(\.\d+){0,2}$/.test(v)
|
|
467
|
+
if (/^[0-9a-f]{7,40}$/i.test(ref)) {
|
|
468
|
+
return { ref, sha: ref, version: versionLike(comment) ? comment : null }
|
|
469
|
+
}
|
|
470
|
+
return { ref, sha: null, version: versionLike(ref) ? ref : null }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Compare two version tags (`v1.1.0` / `1.1` — the leading `v` and a missing
|
|
475
|
+
* minor/patch are tolerated). Returns -1/0/1, or null when either side is
|
|
476
|
+
* unparseable (branch names, bare shas) — callers treat null as "can't
|
|
477
|
+
* assess", never as equality.
|
|
478
|
+
*
|
|
479
|
+
* @param {unknown} a
|
|
480
|
+
* @param {unknown} b
|
|
481
|
+
* @returns {-1|0|1|null}
|
|
482
|
+
*/
|
|
483
|
+
export function compareVersions(a, b) {
|
|
484
|
+
const parse = v => {
|
|
485
|
+
const m = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(String(v ?? '').trim())
|
|
486
|
+
return m ? [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)] : null
|
|
487
|
+
}
|
|
488
|
+
const pa = parse(a)
|
|
489
|
+
const pb = parse(b)
|
|
490
|
+
if (!pa || !pb) return null
|
|
491
|
+
for (let i = 0; i < 3; i++) {
|
|
492
|
+
if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1
|
|
493
|
+
}
|
|
494
|
+
return 0
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Parse `gh run list --json status,conclusion,event,createdAt,databaseId`
|
|
499
|
+
* output into the `RepoRelayRunSchema` shape, most-recent-first as gh emits
|
|
500
|
+
* it. Entries without a usable `databaseId` are dropped (#5502's rerun action
|
|
501
|
+
* needs the id); `createdAt` is normalised to a strict ISO-8601 string.
|
|
502
|
+
*
|
|
503
|
+
* @param {string|null|undefined} json - raw stdout, or null when unavailable.
|
|
504
|
+
* @returns {object[]|null} parsed runs, or null when the payload is
|
|
505
|
+
* absent/unparseable/not an array (the caller degrades with a reason).
|
|
506
|
+
*/
|
|
507
|
+
export function parseRelayRuns(json) {
|
|
508
|
+
if (json === null || json === undefined) return null
|
|
509
|
+
let parsed
|
|
510
|
+
try {
|
|
511
|
+
parsed = JSON.parse(String(json))
|
|
512
|
+
} catch {
|
|
513
|
+
return null
|
|
514
|
+
}
|
|
515
|
+
if (!Array.isArray(parsed)) return null
|
|
516
|
+
const runs = []
|
|
517
|
+
for (const r of parsed) {
|
|
518
|
+
if (!r || typeof r !== 'object') continue
|
|
519
|
+
if (!Number.isInteger(r.databaseId) || r.databaseId < 0) continue
|
|
520
|
+
const str = v => (typeof v === 'string' && v.length > 0 ? v : null)
|
|
521
|
+
const createdMs = typeof r.createdAt === 'string' ? Date.parse(r.createdAt) : NaN
|
|
522
|
+
runs.push({
|
|
523
|
+
databaseId: r.databaseId,
|
|
524
|
+
status: str(r.status),
|
|
525
|
+
conclusion: str(r.conclusion),
|
|
526
|
+
event: str(r.event),
|
|
527
|
+
createdAt: Number.isNaN(createdMs) ? null : new Date(createdMs).toISOString(),
|
|
528
|
+
})
|
|
529
|
+
}
|
|
530
|
+
return runs
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Count consecutive failed conclusions from the most recent run backwards.
|
|
535
|
+
* In-progress runs (no conclusion yet) are skipped — they neither extend nor
|
|
536
|
+
* break the streak; any other conclusion (success, cancelled, …) breaks it.
|
|
537
|
+
*
|
|
538
|
+
* @param {Array<{ conclusion: string|null }>|null|undefined} runs
|
|
539
|
+
* @returns {number}
|
|
540
|
+
*/
|
|
541
|
+
export function computeRelayFailureStreak(runs) {
|
|
542
|
+
let streak = 0
|
|
543
|
+
for (const r of Array.isArray(runs) ? runs : []) {
|
|
544
|
+
const conclusion = r && typeof r.conclusion === 'string' && r.conclusion.length > 0 ? r.conclusion : null
|
|
545
|
+
if (conclusion === null) continue // still running — no signal yet
|
|
546
|
+
if (conclusion === 'failure') {
|
|
547
|
+
streak++
|
|
548
|
+
continue
|
|
549
|
+
}
|
|
550
|
+
break
|
|
551
|
+
}
|
|
552
|
+
return streak
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Classify a repo's relay status into a `RepoRelayVerdictSchema` bucket.
|
|
557
|
+
* Precedence (most urgent first): a broken relay beats a stale pin beats
|
|
558
|
+
* green:
|
|
559
|
+
*
|
|
560
|
+
* - not installed → 'not_installed'
|
|
561
|
+
* - latest CONCLUDED run failed → 'failing'
|
|
562
|
+
* - pinned version < latest release → 'drifted'
|
|
563
|
+
* - latest concluded run succeeded → 'ok'
|
|
564
|
+
* - anything else (no concluded runs, runs
|
|
565
|
+
* unavailable, drift unassessable) → 'unknown'
|
|
566
|
+
*
|
|
567
|
+
* @param {{ installed: boolean, pinnedVersion: string|null,
|
|
568
|
+
* latestVersion: string|null, runs: Array<{ conclusion: string|null }> }} relay
|
|
569
|
+
* @returns {'ok'|'failing'|'drifted'|'not_installed'|'unknown'}
|
|
570
|
+
*/
|
|
571
|
+
export function classifyRelay({ installed, pinnedVersion, latestVersion, runs }) {
|
|
572
|
+
if (!installed) return 'not_installed'
|
|
573
|
+
const latestConcluded = (Array.isArray(runs) ? runs : [])
|
|
574
|
+
.find(r => r && typeof r.conclusion === 'string' && r.conclusion.length > 0)
|
|
575
|
+
if (latestConcluded && latestConcluded.conclusion === 'failure') return 'failing'
|
|
576
|
+
const cmp = compareVersions(pinnedVersion, latestVersion)
|
|
577
|
+
if (cmp !== null && cmp < 0) return 'drifted'
|
|
578
|
+
if (latestConcluded && latestConcluded.conclusion === 'success') return 'ok'
|
|
579
|
+
return 'unknown'
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* #5501: how long a fetched `releases/latest` result stays good across
|
|
584
|
+
* snapshots. Refresh-spamming the Integrations tab must not hammer the GitHub
|
|
585
|
+
* API — within this window the module-level cache answers without a call.
|
|
586
|
+
* Only SUCCESSFUL fetches are cached: a rate-limited/offline attempt degrades
|
|
587
|
+
* that snapshot with a reason and the next refresh retries.
|
|
588
|
+
*/
|
|
589
|
+
export const RELAY_RELEASE_CACHE_TTL_MS = 5 * 60 * 1000
|
|
590
|
+
|
|
591
|
+
/** Module-level latest-release cache: `{ version, fetchedAtMs }` or null. */
|
|
592
|
+
let relayReleaseCache = null
|
|
593
|
+
|
|
594
|
+
/** Test seam: drop the module-level latest-release cache. */
|
|
595
|
+
export function _clearRelayReleaseCache() {
|
|
596
|
+
relayReleaseCache = null
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Fetch the latest blamechris/repo-relay release tag via
|
|
601
|
+
* `gh api repos/blamechris/repo-relay/releases/latest`, honouring the module
|
|
602
|
+
* cache. Never throws — failures resolve `{ version: null, reason }`.
|
|
603
|
+
*
|
|
604
|
+
* @param {Function} execFn - promisified execFile seam.
|
|
605
|
+
* @param {string} ghPath - resolved gh binary path.
|
|
606
|
+
* @param {number} nowMs - snapshot clock (the injected `_now`).
|
|
607
|
+
* @returns {Promise<{ version: string|null, reason: string|null }>}
|
|
608
|
+
*/
|
|
609
|
+
async function fetchLatestRelayRelease(execFn, ghPath, nowMs) {
|
|
610
|
+
if (relayReleaseCache && nowMs >= relayReleaseCache.fetchedAtMs
|
|
611
|
+
&& nowMs - relayReleaseCache.fetchedAtMs < RELAY_RELEASE_CACHE_TTL_MS) {
|
|
612
|
+
return { version: relayReleaseCache.version, reason: null }
|
|
613
|
+
}
|
|
614
|
+
let stdout
|
|
615
|
+
try {
|
|
616
|
+
;({ stdout } = await execFn(ghPath, ['api', `repos/${RELAY_UPSTREAM_REPO}/releases/latest`], EXEC_OPTS))
|
|
617
|
+
} catch (err) {
|
|
618
|
+
return { version: null, reason: execFailureReason(err, 'gh releases/latest') }
|
|
619
|
+
}
|
|
620
|
+
let parsed
|
|
621
|
+
try {
|
|
622
|
+
parsed = JSON.parse(typeof stdout === 'string' ? stdout : '')
|
|
623
|
+
} catch {
|
|
624
|
+
parsed = null
|
|
625
|
+
}
|
|
626
|
+
const version = parsed && typeof parsed === 'object' && typeof parsed.tag_name === 'string' && parsed.tag_name.length > 0
|
|
627
|
+
? parsed.tag_name
|
|
628
|
+
: null
|
|
629
|
+
if (version === null) {
|
|
630
|
+
return { version: null, reason: 'gh releases/latest returned no tag_name' }
|
|
631
|
+
}
|
|
632
|
+
relayReleaseCache = { version, fetchedAtMs: nowMs }
|
|
633
|
+
return { version, reason: null }
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** The quiet `installed: false` relay block (no workflow file → no probing). */
|
|
637
|
+
function relayNotInstalled() {
|
|
638
|
+
return {
|
|
639
|
+
installed: false,
|
|
640
|
+
pinnedVersion: null,
|
|
641
|
+
pinnedSha: null,
|
|
642
|
+
latestVersion: null,
|
|
643
|
+
runs: [],
|
|
644
|
+
failureStreak: 0,
|
|
645
|
+
verdict: 'not_installed',
|
|
646
|
+
driftUnknown: false,
|
|
647
|
+
workflowUrl: null,
|
|
648
|
+
reason: null,
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Survey one repo's repo-relay status (#5501).
|
|
654
|
+
*
|
|
655
|
+
* `installed` + the version pin come from the filesystem alone; the run list
|
|
656
|
+
* and latest release ride on `gh`. Every degradation is per-repo (a `reason`
|
|
657
|
+
* string) — the block always returns. The first applicable reason wins, most
|
|
658
|
+
* actionable first: gh missing → no GitHub remote → run-list failure →
|
|
659
|
+
* latest-release failure → unparseable pin.
|
|
660
|
+
*
|
|
661
|
+
* @param {object} ctx - { readFn, execFn, ghPath, getLatestRelease }
|
|
662
|
+
* @param {{ name: string, path: string }} repo
|
|
663
|
+
* @returns {Promise<object>} a `RepoRelayStatusSchema`-shaped object.
|
|
664
|
+
*/
|
|
665
|
+
async function surveyRepoRelay(ctx, repo) {
|
|
666
|
+
const { readFn, execFn, ghPath, getLatestRelease } = ctx
|
|
667
|
+
|
|
668
|
+
let workflowText = null
|
|
669
|
+
try {
|
|
670
|
+
workflowText = await readFn(join(repo.path, '.github', 'workflows', RELAY_WORKFLOW_FILE), 'utf8')
|
|
671
|
+
} catch {
|
|
672
|
+
workflowText = null
|
|
673
|
+
}
|
|
674
|
+
if (workflowText === null) return relayNotInstalled()
|
|
675
|
+
|
|
676
|
+
const pin = parseRelayPin(workflowText)
|
|
677
|
+
|
|
678
|
+
// GitHub target from the repo's origin remote — same derivation the host
|
|
679
|
+
// survey uses for its PR rollup (survey.js parseGithubOwnerRepo).
|
|
680
|
+
let target = null
|
|
681
|
+
try {
|
|
682
|
+
const { stdout } = await execFn('git', ['remote', 'get-url', 'origin'], { ...EXEC_OPTS, cwd: repo.path })
|
|
683
|
+
target = parseGithubOwnerRepo(typeof stdout === 'string' ? stdout : '')
|
|
684
|
+
} catch {
|
|
685
|
+
target = null
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
let latestVersion = null
|
|
689
|
+
let runs = []
|
|
690
|
+
let reason = null
|
|
691
|
+
|
|
692
|
+
if (!ghPath) {
|
|
693
|
+
reason = GH_MISSING_NOTE
|
|
694
|
+
} else {
|
|
695
|
+
// One shared call per snapshot — `getLatestRelease` memoises the promise.
|
|
696
|
+
const latest = await getLatestRelease()
|
|
697
|
+
latestVersion = latest.version
|
|
698
|
+
|
|
699
|
+
if (!target) {
|
|
700
|
+
reason = NO_GITHUB_REMOTE_REASON
|
|
701
|
+
} else {
|
|
702
|
+
try {
|
|
703
|
+
const { stdout } = await execFn(ghPath, [
|
|
704
|
+
'run', 'list', `--workflow=${RELAY_WORKFLOW_FILE}`, '-R', `${target.owner}/${target.repo}`,
|
|
705
|
+
'--limit', '5', '--json', 'status,conclusion,event,createdAt,databaseId',
|
|
706
|
+
], EXEC_OPTS)
|
|
707
|
+
const parsed = parseRelayRuns(typeof stdout === 'string' ? stdout : '')
|
|
708
|
+
if (parsed === null) {
|
|
709
|
+
reason = 'gh run list produced unparseable output'
|
|
710
|
+
} else {
|
|
711
|
+
runs = parsed
|
|
712
|
+
}
|
|
713
|
+
} catch (err) {
|
|
714
|
+
reason = execFailureReason(err, 'gh run list')
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
if (reason === null && latest.reason !== null) reason = latest.reason
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
if (reason === null && pin === null) {
|
|
722
|
+
reason = 'could not parse the repo-relay uses pin from the workflow'
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const pinnedVersion = pin ? pin.version : null
|
|
726
|
+
const relay = {
|
|
727
|
+
installed: true,
|
|
728
|
+
pinnedVersion,
|
|
729
|
+
pinnedSha: pin ? pin.sha : null,
|
|
730
|
+
latestVersion,
|
|
731
|
+
runs,
|
|
732
|
+
failureStreak: computeRelayFailureStreak(runs),
|
|
733
|
+
verdict: 'unknown',
|
|
734
|
+
// Installed but the pin doesn't resolve to a version (bare sha, branch,
|
|
735
|
+
// unparseable uses line) → drift can't be assessed.
|
|
736
|
+
driftUnknown: pinnedVersion === null,
|
|
737
|
+
workflowUrl: target
|
|
738
|
+
? `https://github.com/${target.owner}/${target.repo}/actions/workflows/${RELAY_WORKFLOW_FILE}`
|
|
739
|
+
: null,
|
|
740
|
+
reason,
|
|
741
|
+
}
|
|
742
|
+
relay.verdict = classifyRelay(relay)
|
|
743
|
+
return relay
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Run `tasks` with a concurrency cap, preserving order. (Same helper shape as
|
|
748
|
+
* survey.js / runners.js — kept local so the modules stay independent.)
|
|
749
|
+
*/
|
|
750
|
+
async function mapWithCap(tasks, cap) {
|
|
751
|
+
const results = new Array(tasks.length)
|
|
752
|
+
let cursor = 0
|
|
753
|
+
const limit = Math.max(1, Math.min(cap, tasks.length || 1))
|
|
754
|
+
async function worker() {
|
|
755
|
+
while (cursor < tasks.length) {
|
|
756
|
+
const i = cursor++
|
|
757
|
+
results[i] = await tasks[i]()
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const workers = []
|
|
761
|
+
for (let i = 0; i < limit; i++) workers.push(worker())
|
|
762
|
+
await Promise.all(workers)
|
|
763
|
+
return results
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** Tally the summary buckets across the surveyed repos. */
|
|
767
|
+
function summarize(repos) {
|
|
768
|
+
const summary = {
|
|
769
|
+
total: 0,
|
|
770
|
+
configured: 0,
|
|
771
|
+
notConfigured: 0,
|
|
772
|
+
degraded: 0,
|
|
773
|
+
// #5501: repo-relay tallies (verdict buckets the operator scans for).
|
|
774
|
+
relayInstalled: 0,
|
|
775
|
+
relayFailing: 0,
|
|
776
|
+
relayDrifted: 0,
|
|
777
|
+
}
|
|
778
|
+
for (const repo of repos) {
|
|
779
|
+
summary.total++
|
|
780
|
+
const relay = repo.repoRelay
|
|
781
|
+
if (relay && relay.installed) summary.relayInstalled++
|
|
782
|
+
if (relay && relay.verdict === 'failing') summary.relayFailing++
|
|
783
|
+
if (relay && relay.verdict === 'drifted') summary.relayDrifted++
|
|
784
|
+
const rm = repo.repoMemory
|
|
785
|
+
if (!rm || !rm.configured) {
|
|
786
|
+
summary.notConfigured++
|
|
787
|
+
continue
|
|
788
|
+
}
|
|
789
|
+
summary.configured++
|
|
790
|
+
if (rm.reason !== null) summary.degraded++
|
|
791
|
+
}
|
|
792
|
+
return summary
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Survey one repo's repo-memory status (#5499).
|
|
797
|
+
*
|
|
798
|
+
* @param {object} ctx - { readFn, statFn, execFn, binPath }
|
|
799
|
+
* @param {{ name: string, path: string }} repo
|
|
800
|
+
* @returns {Promise<object>} a `RepoMemoryStatusSchema`-shaped object.
|
|
801
|
+
*/
|
|
802
|
+
async function surveyRepoMemory(ctx, repo) {
|
|
803
|
+
const { readFn, statFn, execFn, binPath } = ctx
|
|
804
|
+
|
|
805
|
+
let configText = null
|
|
806
|
+
try {
|
|
807
|
+
configText = await readFn(join(repo.path, '.repo-memory.json'), 'utf8')
|
|
808
|
+
} catch {
|
|
809
|
+
configText = null
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
if (configText === null) {
|
|
813
|
+
// Quiet "not configured" row — absence is signal, not an error.
|
|
814
|
+
return { configured: false, summarizer: null, toolGroups: [], cache: null, report: null, reason: null }
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const config = parseRepoMemoryConfig(configText)
|
|
818
|
+
const cache = await surveyCache(statFn, repo.path)
|
|
819
|
+
|
|
820
|
+
let report = null
|
|
821
|
+
let reason = null
|
|
822
|
+
if (!binPath) {
|
|
823
|
+
reason = CLI_MISSING_NOTE
|
|
824
|
+
} else {
|
|
825
|
+
try {
|
|
826
|
+
const { stdout } = await execFn(binPath, ['report', repo.path, '--json', '--diagnostics'], EXEC_OPTS)
|
|
827
|
+
report = parseRepoMemoryReport(typeof stdout === 'string' ? stdout : '')
|
|
828
|
+
if (report === null) reason = 'repo-memory report produced unparseable output'
|
|
829
|
+
} catch (err) {
|
|
830
|
+
reason = execFailureReason(err)
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
return {
|
|
835
|
+
configured: true,
|
|
836
|
+
summarizer: config ? config.summarizer : null,
|
|
837
|
+
toolGroups: config ? config.toolGroups : [],
|
|
838
|
+
cache,
|
|
839
|
+
report,
|
|
840
|
+
reason,
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Survey one repo's integration status: the repo-memory block (#5499) and the
|
|
846
|
+
* repo-relay block (#5501), probed concurrently — they share no state.
|
|
847
|
+
*
|
|
848
|
+
* @param {object} ctx - { readFn, statFn, execFn, binPath, ghPath, getLatestRelease }
|
|
849
|
+
* @param {{ name: string, path: string }} repo
|
|
850
|
+
* @returns {Promise<{ name: string, path: string, repoMemory: object, repoRelay: object }>}
|
|
851
|
+
*/
|
|
852
|
+
async function surveyRepo(ctx, repo) {
|
|
853
|
+
const [repoMemory, repoRelay] = await Promise.all([
|
|
854
|
+
surveyRepoMemory(ctx, repo),
|
|
855
|
+
surveyRepoRelay(ctx, repo),
|
|
856
|
+
])
|
|
857
|
+
return { name: repo.name, path: repo.path, repoMemory, repoRelay }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* Survey integration status across the resolved repo set and produce an
|
|
862
|
+
* `integration_status_snapshot`-shaped result (minus the `type` field).
|
|
863
|
+
*
|
|
864
|
+
* @param {Array<{ name: string, path: string }>} repoSet - from resolveRepoSet.
|
|
865
|
+
* @param {object} [opts]
|
|
866
|
+
* @param {string} [opts.root] - the discovery root the set was resolved under
|
|
867
|
+
* (reported on the snapshot; same value the host survey reports).
|
|
868
|
+
* @param {string} [opts.bin] - explicit repo-memory binary path (skips probing).
|
|
869
|
+
* @param {number} [opts.concurrency]
|
|
870
|
+
* @param {Function} [opts._readFile] - async readFile seam.
|
|
871
|
+
* @param {Function} [opts._stat] - async stat seam.
|
|
872
|
+
* @param {Function} [opts._execFile] - promisified execFile seam.
|
|
873
|
+
* @param {Function} [opts._now] - returns a `Date`.
|
|
874
|
+
* @returns {Promise<{ generatedAt: string, root: string, summary: object, repos: object[], repoMemoryCli: object }>}
|
|
875
|
+
*/
|
|
876
|
+
export async function surveyIntegrations(repoSet, opts = {}) {
|
|
877
|
+
const {
|
|
878
|
+
root = '',
|
|
879
|
+
bin,
|
|
880
|
+
concurrency = DEFAULT_CONCURRENCY,
|
|
881
|
+
_readFile = readFile,
|
|
882
|
+
_stat = stat,
|
|
883
|
+
_execFile = execFileAsync,
|
|
884
|
+
_now = () => new Date(),
|
|
885
|
+
} = opts
|
|
886
|
+
|
|
887
|
+
const now = _now()
|
|
888
|
+
const repos = Array.isArray(repoSet) ? repoSet.filter(r => r && typeof r.path === 'string') : []
|
|
889
|
+
|
|
890
|
+
// One binary probe per snapshot — never one per repo. The gh probe (#5501)
|
|
891
|
+
// follows the same rule.
|
|
892
|
+
const [binPath, ghPath] = await Promise.all([
|
|
893
|
+
resolveRepoMemoryBin(_execFile, bin),
|
|
894
|
+
probeBinOnPath(_execFile, 'gh'),
|
|
895
|
+
])
|
|
896
|
+
|
|
897
|
+
// #5501: the upstream releases/latest lookup is repo-independent — memoise
|
|
898
|
+
// the promise so the first installed repo triggers it and every other repo
|
|
899
|
+
// shares the result (exactly ONE call per snapshot; the module cache then
|
|
900
|
+
// spans snapshots). Never created when no repo has the workflow installed.
|
|
901
|
+
let latestReleasePromise = null
|
|
902
|
+
const getLatestRelease = () => {
|
|
903
|
+
if (!latestReleasePromise) {
|
|
904
|
+
latestReleasePromise = fetchLatestRelayRelease(_execFile, ghPath, now.getTime())
|
|
905
|
+
}
|
|
906
|
+
return latestReleasePromise
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const ctx = { readFn: _readFile, statFn: _stat, execFn: _execFile, binPath, ghPath, getLatestRelease }
|
|
910
|
+
const tasks = repos.map(repo => () => surveyRepo(ctx, repo))
|
|
911
|
+
const surveyed = await mapWithCap(tasks, concurrency)
|
|
912
|
+
|
|
913
|
+
return {
|
|
914
|
+
generatedAt: now.toISOString(),
|
|
915
|
+
root,
|
|
916
|
+
summary: summarize(surveyed),
|
|
917
|
+
repos: surveyed,
|
|
918
|
+
repoMemoryCli: {
|
|
919
|
+
found: binPath !== null,
|
|
920
|
+
path: binPath,
|
|
921
|
+
note: binPath !== null ? null : CLI_MISSING_NOTE,
|
|
922
|
+
},
|
|
923
|
+
ghCli: {
|
|
924
|
+
found: ghPath !== null,
|
|
925
|
+
path: ghPath,
|
|
926
|
+
note: ghPath !== null ? null : GH_MISSING_NOTE,
|
|
927
|
+
},
|
|
928
|
+
}
|
|
929
|
+
}
|