opencode-agent-harness 0.0.0-stage → 0.2.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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +590 -2
- package/bin/agent-harness.js +3059 -0
- package/contrib/global-plugins/README.md +49 -0
- package/contrib/global-plugins/harness-freshness.ts +355 -0
- package/package.json +48 -4
- package/templates/.agents/AGENTS.md +204 -0
- package/templates/.agents/features/INDEX.md +10 -0
- package/templates/.agents/handoffs/README.md +87 -0
- package/templates/.agents/memory/dev-loop.md +59 -0
- package/templates/.agents/memory/domain-map.md +29 -0
- package/templates/.agents/memory/environments.md +35 -0
- package/templates/.agents/memory/flow-map.md +23 -0
- package/templates/.agents/memory/history.md +7 -0
- package/templates/.agents/memory/locations.md +14 -0
- package/templates/.agents/memory/model-routing.md +261 -0
- package/templates/.agents/memory/orchestration.md +183 -0
- package/templates/.agents/memory/owned-files.md +19 -0
- package/templates/.agents/memory/product-principles.md +37 -0
- package/templates/.agents/memory/quality-parameters.md +37 -0
- package/templates/.agents/memory/stack-versions.md +35 -0
- package/templates/.agents/memory/test-design-parameters.md +36 -0
- package/templates/.agents/nightly.json +17 -0
- package/templates/.agents/qa-plans/README.md +70 -0
- package/templates/.agents/qa-runs/README.md +21 -0
- package/templates/.agents/reviews/README.md +47 -0
- package/templates/.agents/rules/00-operating.md +199 -0
- package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
- package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
- package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
- package/templates/.agents/skills/docs/SKILL.md +140 -0
- package/templates/.agents/skills/features/SKILL.md +187 -0
- package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
- package/templates/.agents/skills/handoff/SKILL.md +85 -0
- package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
- package/templates/.agents/skills/planner/SKILL.md +112 -0
- package/templates/.agents/skills/product-manager/SKILL.md +115 -0
- package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
- package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
- package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
- package/templates/.agents/skills/system-architect/SKILL.md +42 -0
- package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
- package/templates/.github/workflows/ci.yml +148 -0
- package/templates/.github/workflows/deploy-uat.yml +95 -0
- package/templates/.github/workflows/nightly.yml +83 -0
- package/templates/.github/workflows/uat-health.yml +41 -0
- package/templates/.husky/pre-push +23 -0
- package/templates/.ignore +28 -0
- package/templates/.opencode/agents/data-engineer.md +37 -0
- package/templates/.opencode/agents/devops-engineer.md +37 -0
- package/templates/.opencode/agents/diagnostics-expert.md +37 -0
- package/templates/.opencode/agents/docs.md +37 -0
- package/templates/.opencode/agents/features.md +21 -0
- package/templates/.opencode/agents/frontend-engineer.md +37 -0
- package/templates/.opencode/agents/handoff.md +21 -0
- package/templates/.opencode/agents/mobile-engineer.md +37 -0
- package/templates/.opencode/agents/planner.md +34 -0
- package/templates/.opencode/agents/product-manager.md +29 -0
- package/templates/.opencode/agents/qa-architect.md +27 -0
- package/templates/.opencode/agents/qa-runner.md +17 -0
- package/templates/.opencode/agents/security-engineer.md +37 -0
- package/templates/.opencode/agents/system-architect.md +37 -0
- package/templates/.opencode/agents/ui-designer.md +37 -0
- package/templates/.opencode/commands/board.md +15 -0
- package/templates/.opencode/commands/checkpoint.md +25 -0
- package/templates/.opencode/commands/feature.md +56 -0
- package/templates/.opencode/commands/finish.md +36 -0
- package/templates/.opencode/commands/next.md +49 -0
- package/templates/.opencode/commands/report.md +55 -0
- package/templates/.opencode/commands/resume.md +39 -0
- package/templates/.opencode/commands/switch-model.md +34 -0
- package/templates/.opencode/commands/tidy.md +49 -0
- package/templates/.opencode/plugins/backlog-notify.ts +57 -0
- package/templates/.opencode/plugins/backlog.ts +272 -0
- package/templates/.opencode/plugins/checkpoint.ts +160 -0
- package/templates/.opencode/plugins/context-guard.ts +1164 -0
- package/templates/.opencode/plugins/diff.ts +85 -0
- package/templates/.opencode/plugins/gates.ts +71 -0
- package/templates/.opencode/plugins/job-notify.ts +241 -0
- package/templates/.opencode/plugins/orient.ts +67 -0
- package/templates/.opencode/plugins/session.ts +89 -0
- package/templates/.opencode/plugins/wait.ts +101 -0
- package/templates/.opencode/plugins/where.ts +70 -0
- package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
- package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
- package/templates/.vercelignore +16 -0
- package/templates/AGENTS.md +27 -0
- package/templates/BACKLOG.md +95 -0
- package/templates/docs/ci-cd-pipeline.md +81 -0
- package/templates/docs/gates.md +128 -0
- package/templates/docs/mcp-integrations.md +97 -0
- package/templates/docs/mobile-testing.md +555 -0
- package/templates/docs/nightly-testing.md +106 -0
- package/templates/docs/wsl-optimizations.md +290 -0
- package/templates/opencode.json +188 -0
- package/templates/scripts/agent-report.js +541 -0
- package/templates/scripts/agent-search.sh +117 -0
- package/templates/scripts/backlog.js +1864 -0
- package/templates/scripts/board-service.sh +207 -0
- package/templates/scripts/checkpoint.js +290 -0
- package/templates/scripts/finalize.js +277 -0
- package/templates/scripts/nightly.js +913 -0
- package/templates/scripts/orient.js +514 -0
- package/templates/scripts/qa/board-client.js +260 -0
- package/templates/scripts/qa/board-lib.js +96 -0
- package/templates/scripts/qa/board-sync.js +469 -0
- package/templates/scripts/qa/capacity-lib.js +916 -0
- package/templates/scripts/qa/check-backlog.js +427 -0
- package/templates/scripts/qa/check-capacity.js +85 -0
- package/templates/scripts/qa/check-ci-policy.js +164 -0
- package/templates/scripts/qa/check-concurrency.js +344 -0
- package/templates/scripts/qa/check-dispatch-config.js +296 -0
- package/templates/scripts/qa/check-docs.js +284 -0
- package/templates/scripts/qa/check-integrate.js +98 -0
- package/templates/scripts/qa/check-linger.js +160 -0
- package/templates/scripts/qa/check-prefix-stability.js +183 -0
- package/templates/scripts/qa/check-product.js +177 -0
- package/templates/scripts/qa/check-qa-plan.js +378 -0
- package/templates/scripts/qa/check-qa-scripts.js +85 -0
- package/templates/scripts/qa/check-quality.js +249 -0
- package/templates/scripts/qa/check-test-wiring.js +253 -0
- package/templates/scripts/qa/ci-triage.js +346 -0
- package/templates/scripts/qa/ci-usage-lib.js +185 -0
- package/templates/scripts/qa/ci-wait-lib.js +294 -0
- package/templates/scripts/qa/command-classifier.js +552 -0
- package/templates/scripts/qa/context-guard-core.js +1618 -0
- package/templates/scripts/qa/diff.js +174 -0
- package/templates/scripts/qa/feature-scaffold.js +224 -0
- package/templates/scripts/qa/fixtures/backlog.md +104 -0
- package/templates/scripts/qa/governance.js +174 -0
- package/templates/scripts/qa/hash-file.js +32 -0
- package/templates/scripts/qa/lease-lib.js +263 -0
- package/templates/scripts/qa/merge-backlog.js +324 -0
- package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
- package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
- package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
- package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
- package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
- package/templates/scripts/qa/mobile-e2e/check-flows.js +453 -0
- package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
- package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
- package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
- package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
- package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
- package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
- package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
- package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
- package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
- package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
- package/templates/scripts/qa/models.allowlist.txt +32 -0
- package/templates/scripts/qa/provider-stats.js +878 -0
- package/templates/scripts/qa/run-clean.js +83 -0
- package/templates/scripts/qa/run-gates.js +212 -0
- package/templates/scripts/qa/run-loop.js +220 -0
- package/templates/scripts/qa/session-recon.js +512 -0
- package/templates/scripts/qa/store-lib.js +324 -0
- package/templates/scripts/qa/tool-lib.js +134 -0
- package/templates/scripts/qa/where.js +214 -0
- package/templates/scripts/qa/wslconfig-merge.js +157 -0
- package/templates/scripts/serve.js +1328 -0
- package/templates/scripts/setup-nightly.sh +185 -0
- package/templates/scripts/setup-tmpfs.sh +374 -0
- package/templates/scripts/ship.js +586 -0
- package/templates/scripts/switch-reasoning-model.ps1 +101 -0
- package/templates/scripts/switch-reasoning-model.sh +104 -0
- package/templates/scripts/wait-for.js +342 -0
- package/templates/scripts/wsl-gpu.sh +180 -0
- package/templates/scripts/wsl-tune.sh +261 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
/*
|
|
4
|
+
* store-lib — one home for reading the local opencode session store.
|
|
5
|
+
*
|
|
6
|
+
* WHY THIS EXISTS (2026-10-16 field review, harness 0.1.163):
|
|
7
|
+
* the telemetry scripts read the store through `opencode db --format json "<SQL>"`.
|
|
8
|
+
* OpenCode **V2 removed the `db` subcommand** (it now prints the root help and
|
|
9
|
+
* exits 0), and it **moved the session tables**: V2 sessions live in
|
|
10
|
+
* `session_v2` + `session_message`, while `session` / `message` / `part` are the
|
|
11
|
+
* frozen legacy mirror. So `provider-stats.js` (→ `report:cost`, `report:recon`,
|
|
12
|
+
* `session_info`) failed on V2 with `Unexpected token 'D'` — the harness lost its
|
|
13
|
+
* own measurement loop. This module is the fix: resolve the store, detect which
|
|
14
|
+
* table generation is authoritative, and run SQL through whichever engine is
|
|
15
|
+
* available, failing loudly (never silently empty) when none is.
|
|
16
|
+
*
|
|
17
|
+
* Engines, in preference order:
|
|
18
|
+
* 1. `node:sqlite` (bundled; sync, no temp files) — Node >= 22.5.
|
|
19
|
+
* 2. `opencode db --format json` — only when the running runtime still has it
|
|
20
|
+
* (V1 line), detected once per process.
|
|
21
|
+
* 3. the `sqlite3` CLI with `-json`.
|
|
22
|
+
* Any engine returning rows wins; all failing is an actionable throw.
|
|
23
|
+
*
|
|
24
|
+
* Table generation (`flavour`) is detected once: `session_v2` + `session_message`
|
|
25
|
+
* present → "v2" (authoritative, includes migrated legacy rows), else "v1".
|
|
26
|
+
*
|
|
27
|
+
* Usage:
|
|
28
|
+
* const store = require("./store-lib.js").openStore();
|
|
29
|
+
* store.query("SELECT count(*) AS n FROM " + store.sessions);
|
|
30
|
+
* store.sessionDirectory("ses_..."); // -> absolute checkout that owns it
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const fs = require("fs");
|
|
34
|
+
const os = require("os");
|
|
35
|
+
const path = require("path");
|
|
36
|
+
const { spawnSync } = require("child_process");
|
|
37
|
+
|
|
38
|
+
const DEFAULT_DATA_REL = path.join(".local", "share", "opencode");
|
|
39
|
+
|
|
40
|
+
/* Parse the `key<whitespace>value` lines `opencode debug paths` prints. Pure:
|
|
41
|
+
* the caller supplies the raw text so this is unit-testable without a CLI. */
|
|
42
|
+
function parseDebugPaths(text) {
|
|
43
|
+
const out = {};
|
|
44
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
45
|
+
const m = line.match(/^\s*([a-z_]+)\s+(.+?)\s*$/i);
|
|
46
|
+
if (m) out[m[1].toLowerCase()] = m[2];
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* Ask the CLI where its store lives. V2's `debug paths` is the supported
|
|
52
|
+
* replacement for the removed `db` subcommand; it prints `data <dir>` and
|
|
53
|
+
* `db <file>`. Best-effort: a missing/old CLI yields `{}`. */
|
|
54
|
+
function cliPaths(opts = {}) {
|
|
55
|
+
const run = opts.spawnSync || spawnSync;
|
|
56
|
+
const bin = opts.opencodeBin || opts.env?.OPENCODE_BIN || "opencode";
|
|
57
|
+
try {
|
|
58
|
+
const r = run(bin, ["debug", "paths"], {
|
|
59
|
+
encoding: "utf8",
|
|
60
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
61
|
+
timeout: opts.timeout || 8000,
|
|
62
|
+
});
|
|
63
|
+
if (r.status !== 0) return {};
|
|
64
|
+
return parseDebugPaths(r.stdout);
|
|
65
|
+
} catch (_) {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* The store directory. `OPENCODE_DATA_DIR` (explicit) → `opencode debug paths`
|
|
71
|
+
* (`data`) → the platform default. */
|
|
72
|
+
function resolveDataRoot(opts = {}) {
|
|
73
|
+
const env = opts.env || process.env;
|
|
74
|
+
const exists = opts.exists || fs.existsSync;
|
|
75
|
+
if (env.OPENCODE_DATA_DIR && exists(env.OPENCODE_DATA_DIR)) return env.OPENCODE_DATA_DIR;
|
|
76
|
+
const paths = opts.paths || cliPaths({ ...opts, env });
|
|
77
|
+
if (paths.data && exists(paths.data)) return paths.data;
|
|
78
|
+
const home = (opts.homedir || os.homedir)();
|
|
79
|
+
return path.join(home, DEFAULT_DATA_REL);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/* The SQLite file. `opencode debug paths` (`db`) wins because V2 may relocate
|
|
83
|
+
* it; else `<data>/opencode.db`. */
|
|
84
|
+
function resolveDbPath(opts = {}) {
|
|
85
|
+
if (opts.dbPath) return opts.dbPath;
|
|
86
|
+
const env = opts.env || process.env;
|
|
87
|
+
const exists = opts.exists || fs.existsSync;
|
|
88
|
+
if (env.OPENCODE_DB && exists(env.OPENCODE_DB)) return env.OPENCODE_DB;
|
|
89
|
+
const paths = opts.paths || cliPaths({ ...opts, env });
|
|
90
|
+
if (paths.db && exists(paths.db)) return paths.db;
|
|
91
|
+
return path.join(resolveDataRoot({ ...opts, paths }), "opencode.db");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------- engines
|
|
95
|
+
|
|
96
|
+
/* `node:sqlite` when present (Node >= 22.5). Kept behind a loader so a missing
|
|
97
|
+
* module is a normal fall-through, not a crash. */
|
|
98
|
+
function nodeSqlite(opts = {}) {
|
|
99
|
+
const requireFn = opts.requireFn || require;
|
|
100
|
+
try {
|
|
101
|
+
const mod = requireFn("node:sqlite");
|
|
102
|
+
if (mod && typeof mod.DatabaseSync === "function") return mod.DatabaseSync;
|
|
103
|
+
} catch (_) {
|
|
104
|
+
/* not available on this runtime */
|
|
105
|
+
}
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/* One process-wide handle per db path. opencode sessions keep writing the file,
|
|
110
|
+
* so a read-only handle is preferred (it never takes a write lock) with a plain
|
|
111
|
+
* handle as fallback for a WAL that wants recovery. */
|
|
112
|
+
const handles = new Map();
|
|
113
|
+
function sqliteHandle(DatabaseSync, dbPath) {
|
|
114
|
+
if (handles.has(dbPath)) return handles.get(dbPath);
|
|
115
|
+
let db = null;
|
|
116
|
+
for (const readOnly of [true, false]) {
|
|
117
|
+
try {
|
|
118
|
+
db = new DatabaseSync(dbPath, readOnly ? { readOnly: true } : {});
|
|
119
|
+
db.exec("PRAGMA busy_timeout = 3000");
|
|
120
|
+
break;
|
|
121
|
+
} catch (_) {
|
|
122
|
+
db = null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
handles.set(dbPath, db);
|
|
126
|
+
return db;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function queryNodeSqlite(dbPath, sql, opts = {}) {
|
|
130
|
+
const DatabaseSync = opts.DatabaseSync || nodeSqlite(opts);
|
|
131
|
+
if (!DatabaseSync) return undefined;
|
|
132
|
+
const db = sqliteHandle(DatabaseSync, dbPath);
|
|
133
|
+
if (!db) return undefined;
|
|
134
|
+
const stmt = db.prepare(sql);
|
|
135
|
+
return stmt.all();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/* `opencode db --format json` — the V1 line. Detected once: V2 prints the root
|
|
139
|
+
* help (status 0, non-JSON) so the probe must assert the shape, not the exit. */
|
|
140
|
+
let dbSubcommand = null;
|
|
141
|
+
function hasDbSubcommand(opts = {}) {
|
|
142
|
+
if (dbSubcommand !== null) return dbSubcommand;
|
|
143
|
+
const run = opts.spawnSync || spawnSync;
|
|
144
|
+
const bin = opts.opencodeBin || opts.env?.OPENCODE_BIN || "opencode";
|
|
145
|
+
try {
|
|
146
|
+
const r = run(bin, ["db", "--format", "json", "SELECT 1 AS ok"], {
|
|
147
|
+
encoding: "utf8",
|
|
148
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
149
|
+
timeout: opts.timeout || 8000,
|
|
150
|
+
});
|
|
151
|
+
const text = String(r.stdout || "").trim();
|
|
152
|
+
dbSubcommand = r.status === 0 && text.startsWith("[");
|
|
153
|
+
} catch (_) {
|
|
154
|
+
dbSubcommand = false;
|
|
155
|
+
}
|
|
156
|
+
return dbSubcommand;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function queryOpencodeDb(dbPath, sql, opts = {}) {
|
|
160
|
+
if (opts.opencodeDb === false) return undefined;
|
|
161
|
+
if (!hasDbSubcommand(opts)) return undefined;
|
|
162
|
+
const run = opts.spawnSync || spawnSync;
|
|
163
|
+
const bin = opts.opencodeBin || opts.env?.OPENCODE_BIN || "opencode";
|
|
164
|
+
let tmp = null;
|
|
165
|
+
let fd = null;
|
|
166
|
+
try {
|
|
167
|
+
// A large dump to a PIPE is truncated by the Bun binary (observed
|
|
168
|
+
// 146,176/194,958 bytes) — write to a real fd instead.
|
|
169
|
+
tmp = path.join(os.tmpdir(), `opencode-db-${process.pid}-${Date.now()}.json`);
|
|
170
|
+
fd = fs.openSync(tmp, "w");
|
|
171
|
+
const r = run(bin, ["db", "--format", "json", sql], { stdio: ["ignore", fd, "pipe"] });
|
|
172
|
+
fs.closeSync(fd);
|
|
173
|
+
fd = null;
|
|
174
|
+
if (r.status !== 0) return undefined;
|
|
175
|
+
const text = fs.readFileSync(tmp, "utf8").trim();
|
|
176
|
+
if (!text) return [];
|
|
177
|
+
const parsed = JSON.parse(text);
|
|
178
|
+
return Array.isArray(parsed) ? parsed : undefined;
|
|
179
|
+
} catch (_) {
|
|
180
|
+
return undefined;
|
|
181
|
+
} finally {
|
|
182
|
+
if (fd != null) {
|
|
183
|
+
try { fs.closeSync(fd); } catch (_) { /* best-effort */ }
|
|
184
|
+
}
|
|
185
|
+
if (tmp) {
|
|
186
|
+
try { fs.rmSync(tmp, { force: true }); } catch (_) { /* best-effort */ }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/* The `sqlite3` CLI with `-json` (SQLite >= 3.33). Last resort so a box without
|
|
192
|
+
* a modern Node still measures. */
|
|
193
|
+
function sqlite3Bin(opts = {}) {
|
|
194
|
+
if (opts.sqlite3) return opts.sqlite3;
|
|
195
|
+
const run = opts.spawnSync || spawnSync;
|
|
196
|
+
for (const cand of ["sqlite3", `${process.env.HOME || ""}/android-sdk/platform-tools/sqlite3`]) {
|
|
197
|
+
if (!cand) continue;
|
|
198
|
+
try {
|
|
199
|
+
const r = run(cand, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 4000 });
|
|
200
|
+
if (r.status === 0 && /\d+\.\d+/.test(String(r.stdout || ""))) return cand;
|
|
201
|
+
} catch (_) {
|
|
202
|
+
/* try the next candidate */
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function querySqlite3Cli(dbPath, sql, opts = {}) {
|
|
209
|
+
const bin = sqlite3Bin(opts);
|
|
210
|
+
if (!bin) return undefined;
|
|
211
|
+
const run = opts.spawnSync || spawnSync;
|
|
212
|
+
try {
|
|
213
|
+
const r = run(bin, ["-json", "-cmd", ".timeout 3000", dbPath, sql], {
|
|
214
|
+
encoding: "utf8",
|
|
215
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
216
|
+
timeout: opts.sqliteTimeout || 30000,
|
|
217
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
218
|
+
});
|
|
219
|
+
if (r.status !== 0) return undefined;
|
|
220
|
+
const text = String(r.stdout || "").trim();
|
|
221
|
+
if (!text) return [];
|
|
222
|
+
const parsed = JSON.parse(text);
|
|
223
|
+
return Array.isArray(parsed) ? parsed : undefined;
|
|
224
|
+
} catch (_) {
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function noEngineError(dbPath) {
|
|
230
|
+
return new Error(
|
|
231
|
+
`opencode store unreachable: no SQLite engine available for ${dbPath}. ` +
|
|
232
|
+
"Install a modern Node (>= 22.5, bundles node:sqlite), run under the opencode runtime " +
|
|
233
|
+
"(V1 `opencode db`), or put `sqlite3` on PATH. Set OPENCODE_DB / OPENCODE_DATA_DIR to override the path."
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/* Run one SQL statement and return rows. `undefined` from every engine becomes
|
|
238
|
+
* a loud throw: an empty aggregate must never be mistaken for "no usage". */
|
|
239
|
+
function makeQuery(dbPath, opts = {}) {
|
|
240
|
+
const engines = opts.engines || [queryNodeSqlite, queryOpencodeDb, querySqlite3Cli];
|
|
241
|
+
return function query(sql) {
|
|
242
|
+
for (const engine of engines) {
|
|
243
|
+
const rows = engine(dbPath, sql, opts);
|
|
244
|
+
if (rows !== undefined) return rows;
|
|
245
|
+
}
|
|
246
|
+
throw noEngineError(dbPath);
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---------------------------------------------------------------- store
|
|
251
|
+
|
|
252
|
+
/* Detect the authoritative table generation. V2 keeps the legacy tables in the
|
|
253
|
+
* file (migrated history), so `session_v2` presence — not emptiness — decides. */
|
|
254
|
+
function detectFlavour(query) {
|
|
255
|
+
try {
|
|
256
|
+
const rows = query(
|
|
257
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('session_v2','session_message')"
|
|
258
|
+
);
|
|
259
|
+
const names = new Set((rows || []).map((r) => r.name));
|
|
260
|
+
if (names.has("session_v2") && names.has("session_message")) {
|
|
261
|
+
return { flavour: "v2", sessions: "session_v2", messages: "session_message", parts: null };
|
|
262
|
+
}
|
|
263
|
+
} catch (_) {
|
|
264
|
+
/* fall through to v1 */
|
|
265
|
+
}
|
|
266
|
+
return { flavour: "v1", sessions: "session", messages: "message", parts: "part" };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/* The table set to query. `flavour` may be forced (tests, --store=v1). */
|
|
270
|
+
function tableSet(query, flavour) {
|
|
271
|
+
if (flavour === "v2") return { flavour: "v2", sessions: "session_v2", messages: "session_message", parts: null };
|
|
272
|
+
if (flavour === "v1") return { flavour: "v1", sessions: "session", messages: "message", parts: "part" };
|
|
273
|
+
return detectFlavour(query);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
let cached = null;
|
|
277
|
+
function openStore(opts = {}) {
|
|
278
|
+
if (opts.dbPath && opts.query) {
|
|
279
|
+
return { ...opts, ...tableSet(opts.query, opts.flavour) };
|
|
280
|
+
}
|
|
281
|
+
const dbPath = resolveDbPath(opts);
|
|
282
|
+
const query = opts.query || makeQuery(dbPath, opts);
|
|
283
|
+
const cacheKey = opts.noCache ? null : dbPath;
|
|
284
|
+
if (cacheKey && cached && cached.dbPath === cacheKey && cached.query === query) return cached;
|
|
285
|
+
const store = { dbPath, dataRoot: path.dirname(dbPath), query, ...tableSet(query, opts.flavour) };
|
|
286
|
+
if (cacheKey) cached = store;
|
|
287
|
+
return store;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/* Which checkout owns a session — the V2 replacement for the plugin-side
|
|
291
|
+
* `ctx.location.directory` capture (a plugin instance is bound to the directory
|
|
292
|
+
* it was loaded for, which is NOT necessarily the session's). Returns `` when the
|
|
293
|
+
* session is absent, never a guess. */
|
|
294
|
+
function sessionDirectory(sessionID, opts = {}) {
|
|
295
|
+
if (!sessionID) return "";
|
|
296
|
+
const store = opts.store || openStore(opts);
|
|
297
|
+
try {
|
|
298
|
+
const rows = store.query(
|
|
299
|
+
`SELECT directory FROM ${store.sessions} WHERE id = '${String(sessionID).replace(/'/g, "''")}' LIMIT 1`
|
|
300
|
+
);
|
|
301
|
+
return (rows && rows[0] && rows[0].directory) || "";
|
|
302
|
+
} catch (_) {
|
|
303
|
+
return "";
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
module.exports = {
|
|
308
|
+
DEFAULT_DATA_REL,
|
|
309
|
+
parseDebugPaths,
|
|
310
|
+
cliPaths,
|
|
311
|
+
resolveDataRoot,
|
|
312
|
+
resolveDbPath,
|
|
313
|
+
makeQuery,
|
|
314
|
+
detectFlavour,
|
|
315
|
+
tableSet,
|
|
316
|
+
openStore,
|
|
317
|
+
sessionDirectory,
|
|
318
|
+
hasDbSubcommand,
|
|
319
|
+
// exported for tests / advanced callers
|
|
320
|
+
queryNodeSqlite,
|
|
321
|
+
queryOpencodeDb,
|
|
322
|
+
querySqlite3Cli,
|
|
323
|
+
noEngineError,
|
|
324
|
+
};
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
/*
|
|
4
|
+
* tool-lib — shared plumbing for the `.opencode/plugins/*.ts` wrappers.
|
|
5
|
+
*
|
|
6
|
+
* The three deterministic-tool wrappers (backlog/checkpoint/session) each need
|
|
7
|
+
* the same two things, and used to carry private copies that drifted:
|
|
8
|
+
* - nodeBin(): opencode runs as a compiled standalone binary, so within its
|
|
9
|
+
* runtime `process.execPath` is the opencode executable, NOT Node. Spawning
|
|
10
|
+
* it with a script path just re-launches opencode (the 0.1.65 regression).
|
|
11
|
+
* Resolve a real Node: an explicit OPENCODE_NODE override, then the runtime's
|
|
12
|
+
* PATH resolver (skipping WSL /mnt entries so a native node beats the
|
|
13
|
+
* interop Windows node.exe), then a bare "node".
|
|
14
|
+
* - sessionRoot(): opencode pins `context.worktree` to the tree the session
|
|
15
|
+
* launched in, so a worktree created MID-session (`backlog worktree` without
|
|
16
|
+
* `--open`) would leave every later call acting on main. The CLI records the
|
|
17
|
+
* worktree against the session id under `.serve/sessions/`; prefer it while
|
|
18
|
+
* the marker path it must contain still exists, else fall back to the launch
|
|
19
|
+
* tree. The marker is per-tool (BACKLOG.md / .agents / the worktree itself)
|
|
20
|
+
* but the resolution lives in ONE place so the three tools cannot disagree.
|
|
21
|
+
*
|
|
22
|
+
* One home per fact: this module is the single source for both.
|
|
23
|
+
*/
|
|
24
|
+
const fs = require("fs");
|
|
25
|
+
const path = require("path");
|
|
26
|
+
const { execFileSync, spawn } = require("child_process");
|
|
27
|
+
|
|
28
|
+
function nodeBin() {
|
|
29
|
+
const override = process.env.OPENCODE_NODE;
|
|
30
|
+
if (override) return override;
|
|
31
|
+
const bun = globalThis.Bun;
|
|
32
|
+
if (bun && typeof bun.which === "function") {
|
|
33
|
+
const pathEnv = String(process.env.PATH || "");
|
|
34
|
+
const native =
|
|
35
|
+
process.platform === "linux"
|
|
36
|
+
? pathEnv
|
|
37
|
+
.split(":")
|
|
38
|
+
.filter((p) => p && !p.startsWith("/mnt/"))
|
|
39
|
+
.join(":")
|
|
40
|
+
: pathEnv;
|
|
41
|
+
const found = bun.which("node", native ? { PATH: native } : {}) || bun.which("node");
|
|
42
|
+
if (found) return found;
|
|
43
|
+
}
|
|
44
|
+
return "node";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* The tree a tool call should act in. `marker` is a path (relative to the
|
|
48
|
+
* candidate root) that must exist for the recorded worktree to be accepted. */
|
|
49
|
+
function sessionRoot(context, marker) {
|
|
50
|
+
const base = (context && (context.worktree || context.directory)) || process.cwd();
|
|
51
|
+
const sessionID = context && context.sessionID ? String(context.sessionID) : "";
|
|
52
|
+
if (!sessionID) return base;
|
|
53
|
+
try {
|
|
54
|
+
const rec = fs
|
|
55
|
+
.readFileSync(path.join(base, ".serve", "sessions", `${sessionID}.worktree`), "utf8")
|
|
56
|
+
.trim();
|
|
57
|
+
if (rec && fs.existsSync(path.join(rec, marker || ""))) return rec;
|
|
58
|
+
} catch {
|
|
59
|
+
/* no mid-session worktree recorded for this session */
|
|
60
|
+
}
|
|
61
|
+
return base;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/* Spawn a deployed script in the session's root. Returns stdout, or a compact
|
|
65
|
+
* error string (never throws into a tool result). `opts`: { marker, env, timeout
|
|
66
|
+
* (ms), label }. */
|
|
67
|
+
function runScript(context, scriptRel, args, opts) {
|
|
68
|
+
const root = sessionRoot(context, opts && opts.marker);
|
|
69
|
+
const script = path.join(root, scriptRel);
|
|
70
|
+
const label = (opts && opts.label) || scriptRel;
|
|
71
|
+
const spawnOpts = {
|
|
72
|
+
cwd: root,
|
|
73
|
+
encoding: "utf8",
|
|
74
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
75
|
+
env: { ...process.env, ...((opts && opts.env) || {}) },
|
|
76
|
+
};
|
|
77
|
+
if (opts && opts.timeout) spawnOpts.timeout = opts.timeout;
|
|
78
|
+
try {
|
|
79
|
+
return execFileSync(nodeBin(), [script, ...args], spawnOpts);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
return `${label}: ${e.message}\n${e.stderr || ""}`;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/* Async twin of runScript. `runScript`'s execFileSync is fine for the quick
|
|
86
|
+
* deterministic tools (backlog/checkpoint/session, sub-second), but a long
|
|
87
|
+
* `wait` (up to 30 min) run synchronously freezes the whole opencode runtime —
|
|
88
|
+
* including the `job-notify` plugin's 3 s progress interval — so a healthy
|
|
89
|
+
* detached run produces no toasts/wakes and looks dead until the wait returns
|
|
90
|
+
* (the F-296 "frozen" session). Spawning frees the event loop so pushes keep
|
|
91
|
+
* flowing while the agent blocks. Resolves `{ code, stdout, stderr, error }`
|
|
92
|
+
* and never rejects; `error` is set when the child could not be spawned.
|
|
93
|
+
* `opts`: { marker, env, timeout (ms), label }. */
|
|
94
|
+
function runScriptAsync(context, scriptRel, args, opts) {
|
|
95
|
+
const root = sessionRoot(context, opts && opts.marker);
|
|
96
|
+
const script = path.join(root, scriptRel);
|
|
97
|
+
const label = (opts && opts.label) || scriptRel;
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
let child;
|
|
100
|
+
try {
|
|
101
|
+
child = spawn(nodeBin(), [script, ...args], {
|
|
102
|
+
cwd: root,
|
|
103
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
104
|
+
env: { ...process.env, ...((opts && opts.env) || {}) },
|
|
105
|
+
});
|
|
106
|
+
} catch (e) {
|
|
107
|
+
resolve({ code: null, stdout: "", stderr: "", error: `${label}: ${e.message}` });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
let stdout = "";
|
|
111
|
+
let stderr = "";
|
|
112
|
+
let timer = null;
|
|
113
|
+
const done = (res) => {
|
|
114
|
+
if (timer) clearTimeout(timer);
|
|
115
|
+
resolve(res);
|
|
116
|
+
};
|
|
117
|
+
if (opts && opts.timeout) {
|
|
118
|
+
timer = setTimeout(() => {
|
|
119
|
+
try {
|
|
120
|
+
child.kill("SIGKILL");
|
|
121
|
+
} catch {
|
|
122
|
+
/* already exited */
|
|
123
|
+
}
|
|
124
|
+
}, opts.timeout);
|
|
125
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
126
|
+
}
|
|
127
|
+
child.stdout.on("data", (d) => (stdout += d));
|
|
128
|
+
child.stderr.on("data", (d) => (stderr += d));
|
|
129
|
+
child.on("error", (e) => done({ code: null, stdout, stderr, error: `${label}: ${e.message}` }));
|
|
130
|
+
child.on("close", (code) => done({ code, stdout, stderr, error: null }));
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = { nodeBin, sessionRoot, runScript, runScriptAsync };
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
/*
|
|
4
|
+
* where — a bounded symbol/owner lookup for agents.
|
|
5
|
+
*
|
|
6
|
+
* The 2026-10 LibraryOS recon measured `grep` as the single most common shell
|
|
7
|
+
* command (1,081 / 14 days) and 95 failed reads on guessed paths. Agents hunt
|
|
8
|
+
* for a symbol by shell-grepping, then read the whole file it lands in. This
|
|
9
|
+
* returns a BOUNDED `file:line: text` hit list for a term, annotated with the
|
|
10
|
+
* feature row(s) that own the hit file (from `.agents/memory/owned-files.md` and
|
|
11
|
+
* the live session leases), and an inverse `--owner <glob>` mode. Index-first
|
|
12
|
+
* (`git grep`, tracked files only), so it never walks node_modules or build
|
|
13
|
+
* trees; a non-git fallback uses ripgrep with default ignore rules.
|
|
14
|
+
*
|
|
15
|
+
* Usage:
|
|
16
|
+
* node scripts/qa/where.js <term> [--files] [--limit N] [--json] [--root <dir>]
|
|
17
|
+
* node scripts/qa/where.js --owner <glob>
|
|
18
|
+
*
|
|
19
|
+
* Dependency-free and injectable (`opts.search`) so parsing, glob matching, and
|
|
20
|
+
* output bounding are unit-testable.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require("fs");
|
|
24
|
+
const path = require("path");
|
|
25
|
+
const { spawnSync } = require("child_process");
|
|
26
|
+
|
|
27
|
+
const DEFAULT_LIMIT = 40;
|
|
28
|
+
const MAX_LINE = 200;
|
|
29
|
+
|
|
30
|
+
/* Parse `.agents/memory/owned-files.md`: `- <ID>: glob[, glob]`. Returns
|
|
31
|
+
* [{ id, globs: [] }]. Pure. */
|
|
32
|
+
function parseOwners(src) {
|
|
33
|
+
const owners = [];
|
|
34
|
+
for (const line of String(src || "").split(/\r?\n/)) {
|
|
35
|
+
const m = line.match(/^\s*[-*]\s+([A-Za-z]+-\d+)\s*:\s*(.+?)\s*$/);
|
|
36
|
+
if (!m) continue;
|
|
37
|
+
const globs = m[2]
|
|
38
|
+
.split(/,|\s+and\s+/)
|
|
39
|
+
.map((g) => g.trim().replace(/`/g, ""))
|
|
40
|
+
.filter(Boolean);
|
|
41
|
+
if (globs.length) owners.push({ id: m[1].toUpperCase(), globs });
|
|
42
|
+
}
|
|
43
|
+
return owners;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/* Glob → RegExp over a repo-relative POSIX path. `**` matches across dirs, `*`
|
|
47
|
+
* within one segment. A glob with no wildcard matches the path or a path under
|
|
48
|
+
* it (so `mobile` covers `mobile/app/x.ts`). Pure. */
|
|
49
|
+
function globToRegExp(glob) {
|
|
50
|
+
const g = String(glob).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
51
|
+
if (!/[*?]/.test(g)) {
|
|
52
|
+
const esc = g.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\/+$/, "");
|
|
53
|
+
return new RegExp(`^${esc}(?:/.*)?$`);
|
|
54
|
+
}
|
|
55
|
+
let re = "";
|
|
56
|
+
for (let i = 0; i < g.length; i++) {
|
|
57
|
+
const c = g[i];
|
|
58
|
+
if (c === "*") {
|
|
59
|
+
if (g[i + 1] === "*") {
|
|
60
|
+
re += ".*";
|
|
61
|
+
i++;
|
|
62
|
+
} else {
|
|
63
|
+
re += "[^/]*";
|
|
64
|
+
}
|
|
65
|
+
} else if (c === "?") {
|
|
66
|
+
re += "[^/]";
|
|
67
|
+
} else {
|
|
68
|
+
re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return new RegExp(`^${re}$`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/* Features whose globs cover `file`. Pure. */
|
|
75
|
+
function ownersForFile(owners, file) {
|
|
76
|
+
const rel = String(file).replace(/\\/g, "/").replace(/^\.\//, "");
|
|
77
|
+
const out = [];
|
|
78
|
+
for (const o of owners) {
|
|
79
|
+
if (o.globs.some((g) => globToRegExp(g).test(rel))) out.push(o.id);
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readOwners(root) {
|
|
85
|
+
try {
|
|
86
|
+
return parseOwners(fs.readFileSync(path.join(root, ".agents", "memory", "owned-files.md"), "utf8"));
|
|
87
|
+
} catch (_) {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/* Default search: `git grep` the tracked index; fall back to ripgrep with the
|
|
93
|
+
* project ignore rules. Returns [{ file, line, text }]. Injectable for tests. */
|
|
94
|
+
function defaultSearch(root, term, opts = {}) {
|
|
95
|
+
const limit = opts.limit || DEFAULT_LIMIT;
|
|
96
|
+
if (opts.files) {
|
|
97
|
+
const ls = spawnSync("git", ["-C", root, "ls-files"], {
|
|
98
|
+
encoding: "utf8",
|
|
99
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
100
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
101
|
+
});
|
|
102
|
+
const re = new RegExp(String(term).replace(/[.+^${}()|[\]\\]/g, "\\$&"), "i");
|
|
103
|
+
return (ls.stdout || "")
|
|
104
|
+
.split(/\r?\n/)
|
|
105
|
+
.filter((f) => f && re.test(f))
|
|
106
|
+
.slice(0, limit)
|
|
107
|
+
.map((f) => ({ file: f.replace(/\\/g, "/"), line: 0, text: "" }));
|
|
108
|
+
}
|
|
109
|
+
const tryGit = spawnSync("git", ["-C", root, "grep", "-n", "-I", "--no-color", "-e", term, "--", "."], {
|
|
110
|
+
encoding: "utf8",
|
|
111
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
112
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
113
|
+
});
|
|
114
|
+
let raw = tryGit.status === 0 || tryGit.status === 1 ? tryGit.stdout || "" : "";
|
|
115
|
+
if (!raw && tryGit.status !== 0 && tryGit.status !== 1) {
|
|
116
|
+
const rg = spawnSync("rg", ["-n", "--no-heading", "--color", "never", "--max-count", "200", "-e", term], {
|
|
117
|
+
cwd: root,
|
|
118
|
+
encoding: "utf8",
|
|
119
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
120
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
121
|
+
});
|
|
122
|
+
raw = rg.stdout || "";
|
|
123
|
+
}
|
|
124
|
+
const hits = [];
|
|
125
|
+
for (const l of raw.split(/\r?\n/)) {
|
|
126
|
+
if (!l.trim()) continue;
|
|
127
|
+
const m = l.match(/^(.+?):(\d+):(.*)$/);
|
|
128
|
+
if (!m) continue;
|
|
129
|
+
hits.push({ file: m[1].replace(/\\/g, "/"), line: Number(m[2]), text: m[3].trim().slice(0, MAX_LINE) });
|
|
130
|
+
if (hits.length >= limit) break;
|
|
131
|
+
}
|
|
132
|
+
return hits;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function parseArgs(argv) {
|
|
136
|
+
const out = { term: null, owner: null, files: false, limit: DEFAULT_LIMIT, json: false, root: null, help: false };
|
|
137
|
+
for (let i = 0; i < argv.length; i++) {
|
|
138
|
+
const a = argv[i];
|
|
139
|
+
if (a === "--owner") out.owner = argv[++i];
|
|
140
|
+
else if (a.startsWith("--owner=")) out.owner = a.slice("--owner=".length);
|
|
141
|
+
else if (a === "--files") out.files = true;
|
|
142
|
+
else if (a === "--json") out.json = true;
|
|
143
|
+
else if (a === "--limit") out.limit = Number(argv[++i]) || DEFAULT_LIMIT;
|
|
144
|
+
else if (a.startsWith("--limit=")) out.limit = Number(a.slice("--limit=".length)) || DEFAULT_LIMIT;
|
|
145
|
+
else if (a === "--root") out.root = argv[++i];
|
|
146
|
+
else if (a.startsWith("--root=")) out.root = a.slice("--root=".length);
|
|
147
|
+
else if (a === "--help" || a === "-h") out.help = true;
|
|
148
|
+
else if (!a.startsWith("-")) out.term = a;
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function filesMode(root, term, limit, search) {
|
|
154
|
+
const hits = (search || defaultSearch)(root, term, { limit, files: true });
|
|
155
|
+
return hits.map((h) => h.file);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function run(opts) {
|
|
159
|
+
const root = path.resolve(opts.root || process.cwd());
|
|
160
|
+
const owners = readOwners(root);
|
|
161
|
+
if (opts.owner) {
|
|
162
|
+
const matched = owners.filter((o) => o.globs.some((g) => globToRegExp(g).test(String(opts.owner).replace(/\\/g, "/"))));
|
|
163
|
+
return { schema: "where/1", mode: "owner", query: opts.owner, owners: matched.map((o) => o.id) };
|
|
164
|
+
}
|
|
165
|
+
const term = String(opts.term || "");
|
|
166
|
+
if (opts.files) {
|
|
167
|
+
const files = filesMode(root, term, opts.limit, opts.search);
|
|
168
|
+
return { schema: "where/1", mode: "files", query: term, files: files.slice(0, opts.limit) };
|
|
169
|
+
}
|
|
170
|
+
const hits = (opts.search || defaultSearch)(root, term, { limit: opts.limit });
|
|
171
|
+
const annotated = hits.map((h) => ({ ...h, owners: ownersForFile(owners, h.file) }));
|
|
172
|
+
return { schema: "where/1", mode: "content", query: term, hits: annotated };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function printHuman(res) {
|
|
176
|
+
if (res.mode === "owner") {
|
|
177
|
+
console.log(`owners of ${res.query}: ${res.owners.join(", ") || "(none registered)"}`);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (res.mode === "files") {
|
|
181
|
+
for (const f of res.files) console.log(f);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
for (const h of res.hits) {
|
|
185
|
+
const own = h.owners.length ? ` [${h.owners.join(",")}]` : "";
|
|
186
|
+
console.log(`${h.file}:${h.line}: ${h.text}${own}`);
|
|
187
|
+
}
|
|
188
|
+
if (!res.hits.length) console.log("(no matches)");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function main() {
|
|
192
|
+
const args = parseArgs(process.argv.slice(2));
|
|
193
|
+
if (args.help || (!args.term && !args.owner)) {
|
|
194
|
+
console.log(
|
|
195
|
+
"Usage: node scripts/qa/where.js <term> [--files] [--limit N] [--json] [--root <dir>]\n" +
|
|
196
|
+
" node scripts/qa/where.js --owner <glob>"
|
|
197
|
+
);
|
|
198
|
+
process.exit(args.help ? 0 : 2);
|
|
199
|
+
}
|
|
200
|
+
const res = run(args);
|
|
201
|
+
if (args.json) console.log(JSON.stringify(res, null, 2));
|
|
202
|
+
else printHuman(res);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (require.main === module) {
|
|
206
|
+
try {
|
|
207
|
+
main();
|
|
208
|
+
} catch (e) {
|
|
209
|
+
console.error("where: " + (e && e.message ? e.message : e));
|
|
210
|
+
process.exit(1);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
module.exports = { parseOwners, globToRegExp, ownersForFile, defaultSearch, parseArgs, run, filesMode, DEFAULT_LIMIT };
|