@indigoai-us/hq-cli 5.345.226 → 5.345.230
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 +156 -0
- package/dist/command-catalog.generated.d.ts +376 -11
- package/dist/command-catalog.generated.js +451 -11
- package/dist/commands/auth.d.ts +2 -2
- package/dist/commands/auth.js +3 -3
- package/dist/commands/core-delegate-w1b.js +92 -69
- package/dist/commands/core-delegate.d.ts +19 -1
- package/dist/commands/core-delegate.js +411 -6
- package/dist/commands/core-dm-bind-native.js +2 -1
- package/dist/commands/core-handoff.d.ts +5 -0
- package/dist/commands/core-handoff.js +1008 -14
- package/dist/commands/core-pin-native.d.ts +1 -0
- package/dist/commands/core-pin-native.js +3 -15
- package/dist/commands/core-register-project-native.d.ts +6 -0
- package/dist/commands/core-register-project-native.js +182 -52
- package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
- package/dist/commands/daemon.js +2 -2
- package/dist/commands/index-cmd.d.ts +3 -1
- package/dist/commands/index-cmd.js +12 -0
- package/dist/commands/lanes-checks.js +1 -1
- package/dist/commands/lanes-session-start.d.ts +1 -2
- package/dist/commands/lanes-session-start.js +9 -145
- package/dist/commands/lanes-shared.d.ts +3 -0
- package/dist/commands/lanes.d.ts +3 -0
- package/dist/commands/lanes.js +94 -27
- package/dist/commands/link.d.ts +8 -3
- package/dist/commands/link.js +14 -17
- package/dist/commands/mcp-registration.d.ts +65 -7
- package/dist/commands/mcp-registration.js +289 -51
- package/dist/commands/mesh.d.ts +12 -0
- package/dist/commands/mesh.js +92 -10
- package/dist/commands/reindex.js +6 -0
- package/dist/commands/repo.d.ts +13 -0
- package/dist/commands/repo.js +39 -1
- package/dist/commands/sync-mode.d.ts +3 -1
- package/dist/commands/sync-mode.js +11 -1
- package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1473 -1043
- package/dist/hq-cloud-sync-runner/package.json +1 -1
- package/dist/lazy-commands.js +3 -4
- package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
- package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
- package/dist/lib/checkpoint-ontology/plan.js +2 -1
- package/dist/lib/core-utils/archive-old-threads.js +5 -2
- package/dist/lib/core-utils/session-company.d.ts +13 -1
- package/dist/lib/core-utils/session-company.js +75 -4
- package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
- package/dist/lib/core-utils/worktree-resume.js +8 -4
- package/dist/lib/daemon/background-qos.d.ts +7 -0
- package/dist/lib/daemon/background-qos.js +13 -0
- package/dist/lib/daemon/catalog.d.ts +9 -0
- package/dist/lib/daemon/catalog.js +8 -1
- package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
- package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
- package/dist/lib/daemon/hook-requests-conduct-link.d.ts +20 -0
- package/dist/lib/daemon/hook-requests-conduct-link.js +105 -0
- package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
- package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
- package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
- package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
- package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
- package/dist/lib/daemon/hook-requests-mesh.js +559 -0
- package/dist/lib/daemon/hook-requests.d.ts +354 -8
- package/dist/lib/daemon/hook-requests.js +1330 -46
- package/dist/lib/daemon/machine-checks.d.ts +12 -2
- package/dist/lib/daemon/machine-checks.js +27 -10
- package/dist/lib/daemon/merge-sections.d.ts +24 -2
- package/dist/lib/daemon/merge-sections.js +58 -16
- package/dist/lib/daemon/ops/policy.js +4 -2
- package/dist/lib/daemon/resolver.js +9 -2
- package/dist/lib/daemon/run.d.ts +11 -7
- package/dist/lib/daemon/run.js +168 -24
- package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
- package/dist/lib/daemon/search-index-worker-v1.js +25 -0
- package/dist/lib/daemon/session-registry.d.ts +0 -1
- package/dist/lib/daemon/session-registry.js +0 -3
- package/dist/lib/daemon/supervisor.d.ts +3 -1
- package/dist/lib/daemon/supervisor.js +1 -1
- package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
- package/dist/lib/daemon/tcc-eperm.js +110 -8
- package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
- package/dist/lib/doctor/fix/process-identity.js +48 -5
- package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
- package/dist/lib/flag-registry-worker-source.generated.js +1 -1
- package/dist/lib/hook-engine/canary-gate.js +1 -0
- package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
- package/dist/lib/hot-channels/adapters/attio.js +2 -1
- package/dist/lib/hot-channels/adapters/meetings.js +2 -1
- package/dist/lib/lanes/company-outposts.d.ts +37 -0
- package/dist/lib/lanes/company-outposts.js +164 -0
- package/dist/lib/lanes/liveness.d.ts +6 -0
- package/dist/lib/lanes/liveness.js +49 -8
- package/dist/lib/lanes/orphan-report.d.ts +15 -0
- package/dist/lib/lanes/orphan-report.js +223 -0
- package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
- package/dist/lib/lanes/orphan-sweep.js +152 -0
- package/dist/lib/lanes/reaper.d.ts +2 -0
- package/dist/lib/lanes/reaper.js +11 -8
- package/dist/lib/lanes/reconcile.d.ts +8 -7
- package/dist/lib/lanes/reconcile.js +39 -0
- package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
- package/dist/lib/mesh/live/backfill-held.js +23 -0
- package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
- package/dist/lib/mesh/live/daemon/mode.js +8 -4
- package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
- package/dist/lib/mesh/live/daemon/run.js +116 -7
- package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
- package/dist/lib/mesh/live/direct-drain.js +315 -0
- package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
- package/dist/lib/mesh/live/emit-replay.js +10 -0
- package/dist/lib/mesh/live/flush.d.ts +15 -0
- package/dist/lib/mesh/live/flush.js +27 -0
- package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
- package/dist/lib/mesh/live/liveness-carry.js +141 -0
- package/dist/lib/mesh/live/spool.d.ts +19 -0
- package/dist/lib/mesh/live/spool.js +80 -0
- package/dist/lib/safe-store.d.ts +2 -0
- package/dist/lib/safe-store.js +8 -6
- package/dist/lib/search-index/index.d.ts +9 -3
- package/dist/lib/search-index/index.js +35 -10
- package/dist/lib/search-index/worker-process.d.ts +9 -0
- package/dist/lib/search-index/worker-process.js +171 -0
- package/dist/lib/session-company-lock.d.ts +3 -1
- package/dist/lib/session-company-lock.js +3 -2
- package/dist/utils/delegate-command-supervisor.d.ts +3 -0
- package/dist/utils/delegate-command-supervisor.js +44 -0
- package/dist/utils/delegate-lock.d.ts +12 -0
- package/dist/utils/delegate-lock.js +88 -0
- package/dist/utils/frontmatter.d.ts +27 -0
- package/dist/utils/frontmatter.js +33 -0
- package/dist/utils/hook-trust.d.ts +1 -0
- package/dist/utils/hook-trust.js +18 -2
- package/dist/utils/host-registration.d.ts +13 -1
- package/dist/utils/host-registration.js +98 -5
- package/dist/utils/package-use-lease.d.ts +1 -1
- package/dist/utils/package-use-lease.js +15 -7
- package/docs/anywhere-runtime.md +17 -0
- package/package.json +9 -8
- package/scripts/check-function-manifest.mjs +17 -3
|
@@ -1,22 +1,27 @@
|
|
|
1
1
|
/** Native implementations of the handoff scaffold command family. */
|
|
2
2
|
import { spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
3
4
|
import { planHqSpawn } from "../utils/hq-spawn.js";
|
|
4
5
|
import * as fs from "node:fs";
|
|
5
6
|
import * as os from "node:os";
|
|
6
7
|
import * as path from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import * as yaml from "js-yaml";
|
|
8
10
|
import { archiveOldThreads } from "../lib/core-utils/archive-old-threads.js";
|
|
9
11
|
import { summarizeHqStatus } from "../lib/core-utils/hq-status-summary.js";
|
|
12
|
+
import { matchingSecretPatterns } from "../lib/core-utils/secret-patterns.js";
|
|
10
13
|
import { enqueueSessionEvent } from "../lib/mesh/live/enqueue.js";
|
|
11
14
|
import { renderIndexTarget } from "../lib/index-render/index.js";
|
|
12
15
|
import { defaultBackgroundDependencies, runBackgroundLauncher, } from "../lib/search-index/background.js";
|
|
13
16
|
import { resolveLiveRoot } from "../utils/hq-roots.js";
|
|
14
17
|
import { runBundledScript } from "../utils/run-bundled-script.js";
|
|
15
18
|
import { describeCoreCommand } from "./core-command-catalog.js";
|
|
19
|
+
import { subprocess } from "./core-delegate.js";
|
|
16
20
|
import { CLOUD_OFF_EXIT_CODE } from "./cloud-off-gate.js";
|
|
17
21
|
import { shellDisplayPath } from "../lib/core-utils/shell-display-path.js";
|
|
18
22
|
import { fingerprintTrailerArgs, offlineFingerprint } from "../lib/fingerprint/offline.js";
|
|
19
23
|
import { compactJson, isRecord, jqTruthy, prettyJson, runHandoffOpenSteps, shellDate, } from "./core-handoff-open-steps.js";
|
|
24
|
+
import { runHandoffKnowledgeCommit } from "./core-bucket-c-handoff-knowledge-native.js";
|
|
20
25
|
export { runHandoffOpenSteps };
|
|
21
26
|
const ASSETS = {
|
|
22
27
|
finalize: "core/scripts/handoff-finalize.sh",
|
|
@@ -101,12 +106,12 @@ function dayStamp(date) {
|
|
|
101
106
|
function timeStamp(date) {
|
|
102
107
|
return date.toISOString().slice(11, 19).replaceAll(":", "");
|
|
103
108
|
}
|
|
104
|
-
function git(args, cwd) {
|
|
109
|
+
function git(args, cwd, input) {
|
|
105
110
|
const result = spawnSync("git", args, {
|
|
106
111
|
cwd,
|
|
107
112
|
env: process.env,
|
|
108
113
|
encoding: "utf8",
|
|
109
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
114
|
+
...(input === undefined ? { stdio: ["ignore", "pipe", "pipe"] } : { input, stdio: ["pipe", "pipe", "pipe"] }),
|
|
110
115
|
});
|
|
111
116
|
if (result.error)
|
|
112
117
|
return { code: 127, stdout: "", stderr: result.error.message };
|
|
@@ -323,10 +328,11 @@ function finalizeGitProbe(root) {
|
|
|
323
328
|
function printGitStatus(root) {
|
|
324
329
|
return git(["status", "--porcelain"], root).stdout;
|
|
325
330
|
}
|
|
331
|
+
function stagePathExists(root, pathname) {
|
|
332
|
+
return fs.existsSync(path.join(root, pathname)) || git(["status", "--porcelain", "--", pathname], root).stdout !== "";
|
|
333
|
+
}
|
|
326
334
|
function stagePath(root, pathname) {
|
|
327
|
-
|
|
328
|
-
const exists = fs.existsSync(absolute) || git(["status", "--porcelain", "--", pathname], root).stdout !== "";
|
|
329
|
-
if (!exists)
|
|
335
|
+
if (!stagePathExists(root, pathname))
|
|
330
336
|
return { attempted: false, ok: false, failed: false };
|
|
331
337
|
if (git(["add", "--", pathname], root).code === 0)
|
|
332
338
|
return { attempted: true, ok: true, failed: false };
|
|
@@ -340,6 +346,31 @@ function stagePath(root, pathname) {
|
|
|
340
346
|
}
|
|
341
347
|
return { attempted: true, ok: false, failed: true };
|
|
342
348
|
}
|
|
349
|
+
// Stages every path with one `git add` instead of one per path. The paths go
|
|
350
|
+
// to git on stdin, NUL-separated, never through a shell. A dry run comes first:
|
|
351
|
+
// it stages nothing and fails on the inputs that make a real `git add` stage
|
|
352
|
+
// some paths and still exit non-zero (ignored paths), so the real batch only
|
|
353
|
+
// runs when it is expected to succeed, and a real batch that fails anyway dies
|
|
354
|
+
// before git writes the index. Whenever either step fails (an ignored or
|
|
355
|
+
// unstageable path, or a git older than 2.25 without --pathspec-from-file),
|
|
356
|
+
// every path goes through the per-path stagePath() exactly as before, from an
|
|
357
|
+
// unchanged index, so staged, skipped and failed paths are reported as today.
|
|
358
|
+
function stagePaths(root, pathnames) {
|
|
359
|
+
const perPath = () => pathnames.map((pathname) => stagePath(root, pathname));
|
|
360
|
+
if (pathnames.some((pathname) => pathname.includes("\0")))
|
|
361
|
+
return perPath();
|
|
362
|
+
const exists = pathnames.map((pathname) => stagePathExists(root, pathname));
|
|
363
|
+
const candidates = pathnames.filter((_, index) => exists[index]);
|
|
364
|
+
if (candidates.length === 0)
|
|
365
|
+
return pathnames.map(() => ({ attempted: false, ok: false, failed: false }));
|
|
366
|
+
const input = `${candidates.join("\0")}\0`;
|
|
367
|
+
const batchArgs = ["--pathspec-from-file=-", "--pathspec-file-nul"];
|
|
368
|
+
if (git(["add", "--dry-run", ...batchArgs], root, input).code !== 0)
|
|
369
|
+
return perPath();
|
|
370
|
+
if (git(["add", ...batchArgs], root, input).code !== 0)
|
|
371
|
+
return perPath();
|
|
372
|
+
return exists.map((attempted) => ({ attempted, ok: attempted, failed: false }));
|
|
373
|
+
}
|
|
343
374
|
function tidyGitMessage(value) {
|
|
344
375
|
const flattened = value.replace(/[\r\n]/g, " ").replace(/ */g, " ").replace(/^ | $/g, "");
|
|
345
376
|
return Buffer.from(flattened).subarray(0, 500).toString("utf8").replace(/\uFFFD+$/, "");
|
|
@@ -571,15 +602,15 @@ export function runHandoffFinalize(args, context) {
|
|
|
571
602
|
let staged = 0;
|
|
572
603
|
const stageFailures = [];
|
|
573
604
|
if (probe.hasGit) {
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
const result =
|
|
605
|
+
const stageable = explicit.filter((pathname) => pathname);
|
|
606
|
+
const results = stagePaths(root, stageable);
|
|
607
|
+
stageable.forEach((pathname, index) => {
|
|
608
|
+
const result = results[index];
|
|
578
609
|
if (result.ok)
|
|
579
610
|
staged += 1;
|
|
580
611
|
else if (result.failed)
|
|
581
612
|
stageFailures.push(pathname);
|
|
582
|
-
}
|
|
613
|
+
});
|
|
583
614
|
}
|
|
584
615
|
let hqCommitted = false;
|
|
585
616
|
let commitStatus = probe.hasGit ? "nothing-to-commit" : "no-git-checkout";
|
|
@@ -1110,6 +1141,927 @@ export function runHandoffPostWorker(args, context) {
|
|
|
1110
1141
|
log("handoff-post complete");
|
|
1111
1142
|
return { code: 0, stdout: "", stderr: "" };
|
|
1112
1143
|
}
|
|
1144
|
+
function jqAlt(value, fallback) {
|
|
1145
|
+
return value === null || value === undefined || value === false ? fallback : value;
|
|
1146
|
+
}
|
|
1147
|
+
function jqText(value) {
|
|
1148
|
+
if (typeof value === "string")
|
|
1149
|
+
return value;
|
|
1150
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1151
|
+
return String(value);
|
|
1152
|
+
if (value === null || value === undefined)
|
|
1153
|
+
return "";
|
|
1154
|
+
return JSON.stringify(value) ?? "";
|
|
1155
|
+
}
|
|
1156
|
+
function interp(value, fallback = "") {
|
|
1157
|
+
return jqText(jqAlt(value, fallback));
|
|
1158
|
+
}
|
|
1159
|
+
function readJsonFile(file) {
|
|
1160
|
+
try {
|
|
1161
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1162
|
+
}
|
|
1163
|
+
catch {
|
|
1164
|
+
return undefined;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
function isDirectory(file) {
|
|
1168
|
+
try {
|
|
1169
|
+
return fs.statSync(file).isDirectory();
|
|
1170
|
+
}
|
|
1171
|
+
catch {
|
|
1172
|
+
return false;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
function isFile(file) {
|
|
1176
|
+
try {
|
|
1177
|
+
return fs.statSync(file).isFile();
|
|
1178
|
+
}
|
|
1179
|
+
catch {
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
/** jq `if type == string then . elif one-string-array then .[0] else empty end`. */
|
|
1184
|
+
function singleCompanyOutput(value) {
|
|
1185
|
+
if (typeof value === "string")
|
|
1186
|
+
return { emitted: true, text: value.split(/\r?\n/, 1)[0] ?? "" };
|
|
1187
|
+
if (Array.isArray(value) && value.length === 1 && typeof value[0] === "string") {
|
|
1188
|
+
return { emitted: true, text: value[0].split(/\r?\n/, 1)[0] ?? "" };
|
|
1189
|
+
}
|
|
1190
|
+
return { emitted: false, text: "" };
|
|
1191
|
+
}
|
|
1192
|
+
function handoffPointerRoot(context) {
|
|
1193
|
+
return process.env.HQ_ROOT || context.cwd;
|
|
1194
|
+
}
|
|
1195
|
+
export function runHandoffPointerCompany(args, context) {
|
|
1196
|
+
const hqRoot = handoffPointerRoot(context);
|
|
1197
|
+
const pointer = args[0] || path.join(hqRoot, "workspace/threads/handoff.json");
|
|
1198
|
+
if (!isFile(pointer))
|
|
1199
|
+
return { code: 0, stdout: "", stderr: "" };
|
|
1200
|
+
const doc = readJsonFile(pointer);
|
|
1201
|
+
let slug = "";
|
|
1202
|
+
let emitted = false;
|
|
1203
|
+
if (isRecord(doc)) {
|
|
1204
|
+
const company = singleCompanyOutput(jqAlt(doc.company, undefined) === undefined ? undefined : doc.company);
|
|
1205
|
+
const companies = singleCompanyOutput(doc.companies);
|
|
1206
|
+
// `.company // empty` emits nothing for null/false and a line for a string, including "".
|
|
1207
|
+
if (doc.company !== undefined && doc.company !== null && doc.company !== false && company.emitted) {
|
|
1208
|
+
slug = company.text;
|
|
1209
|
+
emitted = true;
|
|
1210
|
+
}
|
|
1211
|
+
else if (doc.companies !== undefined && doc.companies !== null && doc.companies !== false && companies.emitted) {
|
|
1212
|
+
slug = companies.text;
|
|
1213
|
+
emitted = true;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
if (!emitted || slug === "") {
|
|
1217
|
+
const threadRaw = isRecord(doc) && typeof doc.thread_path === "string" ? doc.thread_path : "";
|
|
1218
|
+
if (threadRaw) {
|
|
1219
|
+
const threadPath = path.isAbsolute(threadRaw) ? threadRaw : path.join(hqRoot, threadRaw);
|
|
1220
|
+
if (isFile(threadPath)) {
|
|
1221
|
+
const thread = readJsonFile(threadPath);
|
|
1222
|
+
const metadata = isRecord(thread) ? thread.metadata : undefined;
|
|
1223
|
+
if (isRecord(metadata) && metadata.company !== undefined && metadata.company !== null && metadata.company !== false) {
|
|
1224
|
+
const company = singleCompanyOutput(metadata.company);
|
|
1225
|
+
if (company.emitted)
|
|
1226
|
+
slug = company.text;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(slug))
|
|
1232
|
+
return { code: 0, stdout: "", stderr: "" };
|
|
1233
|
+
return { code: 0, stdout: `${slug}\n`, stderr: "" };
|
|
1234
|
+
}
|
|
1235
|
+
function parseNamedArgs(args, known, label) {
|
|
1236
|
+
const values = {};
|
|
1237
|
+
const flags = new Set();
|
|
1238
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1239
|
+
const token = args[index] ?? "";
|
|
1240
|
+
if (!token.startsWith("--"))
|
|
1241
|
+
return { values, flags, error: { code: 2, stdout: "", stderr: `${label}: unknown argument: ${token}\n` } };
|
|
1242
|
+
if (!known.has(token))
|
|
1243
|
+
return { values, flags, error: { code: 2, stdout: "", stderr: `${label}: unknown argument: ${token}\n` } };
|
|
1244
|
+
const value = args[index + 1];
|
|
1245
|
+
if (value === undefined)
|
|
1246
|
+
return { values, flags, error: { code: 2, stdout: "", stderr: `${label}: unknown argument: ${token}\n` } };
|
|
1247
|
+
values[token] = value;
|
|
1248
|
+
flags.add(token);
|
|
1249
|
+
index += 1;
|
|
1250
|
+
}
|
|
1251
|
+
return { values, flags };
|
|
1252
|
+
}
|
|
1253
|
+
function hqCoreDeficiencies(thread) {
|
|
1254
|
+
if (!isRecord(thread) || !Array.isArray(thread.deficiencies))
|
|
1255
|
+
return [];
|
|
1256
|
+
return thread.deficiencies.filter((item) => isRecord(item) && item.kind === "hq-core");
|
|
1257
|
+
}
|
|
1258
|
+
function shortThreadId(threadId) {
|
|
1259
|
+
const dash = threadId.lastIndexOf("-");
|
|
1260
|
+
let short = dash >= 0 ? threadId.slice(dash + 1) : threadId;
|
|
1261
|
+
if (!short || short === threadId)
|
|
1262
|
+
short = threadId.slice(0, 12);
|
|
1263
|
+
return short.replace(/[^A-Za-z0-9._-]/g, "-");
|
|
1264
|
+
}
|
|
1265
|
+
function evidenceText(item) {
|
|
1266
|
+
const raw = jqAlt(item.evidence, "");
|
|
1267
|
+
const text = jqText(raw);
|
|
1268
|
+
return text.length > 0 ? text : "NONE (do not apply; list under Not applied)";
|
|
1269
|
+
}
|
|
1270
|
+
function groupByLever(items) {
|
|
1271
|
+
const groups = new Map();
|
|
1272
|
+
for (const item of items) {
|
|
1273
|
+
const key = interp(item.lever, "unknown");
|
|
1274
|
+
const list = groups.get(key);
|
|
1275
|
+
if (list)
|
|
1276
|
+
list.push(item);
|
|
1277
|
+
else
|
|
1278
|
+
groups.set(key, [item]);
|
|
1279
|
+
}
|
|
1280
|
+
return [...groups.entries()]
|
|
1281
|
+
.sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0))
|
|
1282
|
+
.map((entry) => entry[1]);
|
|
1283
|
+
}
|
|
1284
|
+
function renderBuilderBrief(threadId, branch, items) {
|
|
1285
|
+
const header = [
|
|
1286
|
+
"# Handoff builder fix brief",
|
|
1287
|
+
"",
|
|
1288
|
+
`Thread: ${threadId}`,
|
|
1289
|
+
"Repo: repos/private/hq-core-staging (GitHub indigoai-us/hq-core-staging)",
|
|
1290
|
+
`Branch: ${branch} (create off origin/main)`,
|
|
1291
|
+
"",
|
|
1292
|
+
"## Rules",
|
|
1293
|
+
"",
|
|
1294
|
+
`1. Fetch origin, then create ${branch} off origin/main. Anchor every git command with git -C repos/private/hq-core-staging and every gh command with -R indigoai-us/hq-core-staging.`,
|
|
1295
|
+
"2. Apply the fixes below grouped by lever, one commit per lever. Only touch files inside hq-core-staging.",
|
|
1296
|
+
"3. Leave an item out and list it under 'Not applied' with the reason when it has no evidence, the fix is outside hq-core, or its tests fail after the change (revert that item's commit).",
|
|
1297
|
+
"4. Run the tests named in or next to every touched area (core/scripts/tests/*.test.sh that cover the touched scripts, and the checks .github/workflows/pr-checks.yml runs for those paths), plus the leak scan the repo CI runs. Never skip, loosen, or delete a test.",
|
|
1298
|
+
`5. Push the branch and open exactly one PR against main. The PR body lists each applied deficiency with its lever, summary, and evidence, links thread ${threadId}, and has a 'Not applied' section (write 'None' when empty).`,
|
|
1299
|
+
"6. When the diff touches .claude/skills or .claude/commands, add the manual-copy label, then push one more commit so CI reruns with the label.",
|
|
1300
|
+
"7. Never merge, never run gh pr merge, never use --admin, never push to main.",
|
|
1301
|
+
"8. Finish with one line: 'pr: <url>' or 'pr: none (<reason>)'.",
|
|
1302
|
+
"",
|
|
1303
|
+
"## Deficiencies",
|
|
1304
|
+
"",
|
|
1305
|
+
"",
|
|
1306
|
+
].join("\n");
|
|
1307
|
+
const groups = groupByLever(items).map((grouped) => {
|
|
1308
|
+
const lever = interp(grouped[0]?.lever, "unknown");
|
|
1309
|
+
const body = grouped.map((item) => [
|
|
1310
|
+
`- Summary: ${interp(item.summary)}`,
|
|
1311
|
+
` Severity: ${interp(item.severity, "unknown")}`,
|
|
1312
|
+
` Evidence: ${evidenceText(item)}`,
|
|
1313
|
+
` Proposed fix: ${interp(item.proposed_fix)}`,
|
|
1314
|
+
].join("\n")).join("\n");
|
|
1315
|
+
return `### Lever: ${lever}\n${body}\n`;
|
|
1316
|
+
});
|
|
1317
|
+
return `${header}${groups.join("\n")}${groups.length > 0 ? "\n" : ""}`;
|
|
1318
|
+
}
|
|
1319
|
+
function gitPushProbe(staging, cwd) {
|
|
1320
|
+
const ssh = process.env.GIT_SSH_COMMAND ?? "ssh";
|
|
1321
|
+
const result = subprocess("git", [
|
|
1322
|
+
"-C", staging, "push", "--dry-run", "--force", "--quiet", "origin", "HEAD:refs/heads/handoff-fix/route-probe",
|
|
1323
|
+
], cwd, {
|
|
1324
|
+
input: "",
|
|
1325
|
+
stdout: "ignore",
|
|
1326
|
+
stderr: "ignore",
|
|
1327
|
+
env: { GIT_TERMINAL_PROMPT: "0", GIT_SSH_COMMAND: `${ssh} -o BatchMode=yes` },
|
|
1328
|
+
});
|
|
1329
|
+
return result.code === 0;
|
|
1330
|
+
}
|
|
1331
|
+
export function runHandoffBuilderRoute(args, context) {
|
|
1332
|
+
const parsed = parseNamedArgs(args, new Set(["--root", "--thread", "--brief-out"]), "handoff-builder-route");
|
|
1333
|
+
if (parsed.error)
|
|
1334
|
+
return parsed.error;
|
|
1335
|
+
const root = parsed.values["--root"] || context.root;
|
|
1336
|
+
const thread = parsed.values["--thread"] ?? "";
|
|
1337
|
+
let briefOut = parsed.values["--brief-out"] ?? "";
|
|
1338
|
+
if (thread && !isFile(path.isAbsolute(thread) ? thread : path.resolve(context.cwd, thread))) {
|
|
1339
|
+
return { code: 2, stdout: "", stderr: `handoff-builder-route: thread not found: ${thread}\n` };
|
|
1340
|
+
}
|
|
1341
|
+
const staging = path.join(root, "repos/private/hq-core-staging");
|
|
1342
|
+
let routeReason = "";
|
|
1343
|
+
if ((process.env.HQ_HANDOFF_BUILDER_ROUTE ?? "1") === "0")
|
|
1344
|
+
routeReason = "builder route disabled (HQ_HANDOFF_BUILDER_ROUTE=0)";
|
|
1345
|
+
else if (!isDirectory(staging))
|
|
1346
|
+
routeReason = "no hq-core-staging repo";
|
|
1347
|
+
else if (subprocess("git", ["-C", staging, "rev-parse", "--git-dir"], context.cwd, { stdout: "ignore", stderr: "ignore" }).code !== 0) {
|
|
1348
|
+
routeReason = "hq-core-staging is not a git repo";
|
|
1349
|
+
}
|
|
1350
|
+
else if (!gitPushProbe(staging, context.cwd))
|
|
1351
|
+
routeReason = "git push --dry-run to hq-core-staging failed";
|
|
1352
|
+
if (routeReason)
|
|
1353
|
+
return { code: 0, stdout: `route: public (${routeReason})\n`, stderr: "" };
|
|
1354
|
+
if (!thread)
|
|
1355
|
+
return { code: 0, stdout: "route: builder\n", stderr: "" };
|
|
1356
|
+
const threadFile = path.isAbsolute(thread) ? thread : path.resolve(context.cwd, thread);
|
|
1357
|
+
const threadDoc = readJsonFile(threadFile);
|
|
1358
|
+
if (threadDoc === undefined)
|
|
1359
|
+
return { code: 1, stdout: "", stderr: `handoff-builder-route: invalid thread JSON: ${thread}\n` };
|
|
1360
|
+
const items = hqCoreDeficiencies(threadDoc);
|
|
1361
|
+
if (items.length === 0)
|
|
1362
|
+
return { code: 0, stdout: "route: builder\nbrief: none (no hq-core deficiencies)\n", stderr: "" };
|
|
1363
|
+
const rawId = isRecord(threadDoc) ? threadDoc.thread_id : undefined;
|
|
1364
|
+
const threadId = rawId === null || rawId === undefined || rawId === false || rawId === ""
|
|
1365
|
+
? path.basename(threadFile, ".json")
|
|
1366
|
+
: jqText(rawId);
|
|
1367
|
+
const shortId = shortThreadId(threadId);
|
|
1368
|
+
const branch = `handoff-fix/${shortId}`;
|
|
1369
|
+
if (!briefOut)
|
|
1370
|
+
briefOut = path.join(root, "workspace/handoff-builder", `${shortId}.md`);
|
|
1371
|
+
fs.mkdirSync(path.dirname(briefOut), { recursive: true });
|
|
1372
|
+
fs.writeFileSync(briefOut, renderBuilderBrief(threadId, branch, items));
|
|
1373
|
+
return { code: 0, stdout: `route: builder\nbrief: ${briefOut}\n`, stderr: "" };
|
|
1374
|
+
}
|
|
1375
|
+
const AUTOFILE_WINDOW_SECONDS = 604800;
|
|
1376
|
+
const IMPACT_PATTERN = /\bblocked\b|\bdenied\b|fail(?:ed|s)? to write|failed write|write (?:failed|was blocked|was denied)|could not write|cannot write|unable to write/i;
|
|
1377
|
+
function sha256(value) {
|
|
1378
|
+
return createHash("sha256").update(value).digest("hex");
|
|
1379
|
+
}
|
|
1380
|
+
function severityRank(item) {
|
|
1381
|
+
const severity = jqAlt(item.severity, "low");
|
|
1382
|
+
const key = typeof severity === "string" ? severity : jqText(severity);
|
|
1383
|
+
const ranks = { high: 0, medium: 1, low: 2 };
|
|
1384
|
+
return ranks[key] ?? 3;
|
|
1385
|
+
}
|
|
1386
|
+
function autofileBody(items, impact, systemInfo) {
|
|
1387
|
+
const emit = (text) => `${text}\n`;
|
|
1388
|
+
const parts = [
|
|
1389
|
+
emit(`src=handoff impact=${impact}`),
|
|
1390
|
+
emit("Auto-filed by /handoff: hq-core deficiencies from one session.\n"),
|
|
1391
|
+
];
|
|
1392
|
+
items.forEach((item, index) => {
|
|
1393
|
+
parts.push(emit(`## ${index + 1}. ${interp(item.summary)}\n`), emit(`- lever: ${interp(item.lever)}`), emit(`- severity: ${interp(item.severity)}`), emit(`- summary: ${interp(item.summary)}`), emit(`- evidence: ${interp(item.evidence)}`), emit(`- proposed fix: ${interp(item.proposed_fix)}\n`));
|
|
1394
|
+
});
|
|
1395
|
+
parts.push(emit("## system_info\n"), emit("```json"), emit(JSON.stringify(systemInfo)), emit("```"));
|
|
1396
|
+
return parts.join("");
|
|
1397
|
+
}
|
|
1398
|
+
function feedbackId(output) {
|
|
1399
|
+
const match = /(?:^|[^A-Za-z0-9_])[Ii][Dd][:= ]+([A-Za-z0-9_-]+)/.exec(output);
|
|
1400
|
+
return match?.[1] || "unknown";
|
|
1401
|
+
}
|
|
1402
|
+
export function runHandoffAutofile(args, context) {
|
|
1403
|
+
const parsed = parseNamedArgs(args, new Set(["--thread", "--root"]), "handoff-autofile");
|
|
1404
|
+
if (parsed.error)
|
|
1405
|
+
return parsed.error;
|
|
1406
|
+
const thread = parsed.values["--thread"] ?? "";
|
|
1407
|
+
const root = parsed.values["--root"] || context.root;
|
|
1408
|
+
if (!parsed.flags.has("--thread") || thread === "")
|
|
1409
|
+
return { code: 2, stdout: "", stderr: "handoff-autofile: --thread is required\n" };
|
|
1410
|
+
const threadFile = path.isAbsolute(thread) ? thread : path.resolve(context.cwd, thread);
|
|
1411
|
+
if (!isFile(threadFile))
|
|
1412
|
+
return { code: 2, stdout: "", stderr: `handoff-autofile: thread not found: ${thread}\n` };
|
|
1413
|
+
if ((process.env.HQ_HANDOFF_AUTOFILE ?? "1") === "0") {
|
|
1414
|
+
return { code: 0, stdout: "skipped: auto-filing disabled (HQ_HANDOFF_AUTOFILE=0)\n", stderr: "" };
|
|
1415
|
+
}
|
|
1416
|
+
const staging = path.join(root, "repos/private/hq-core-staging");
|
|
1417
|
+
if (isDirectory(staging)) {
|
|
1418
|
+
const route = runHandoffBuilderRoute(["--root", root], context);
|
|
1419
|
+
if (route.stdout.replace(/\n+$/, "") === "route: builder")
|
|
1420
|
+
return { code: 0, stdout: "skipped: builder machine\n", stderr: "" };
|
|
1421
|
+
}
|
|
1422
|
+
const threadDoc = readJsonFile(threadFile);
|
|
1423
|
+
if (threadDoc === undefined)
|
|
1424
|
+
return { code: 1, stdout: "", stderr: `handoff-autofile: invalid thread JSON: ${thread}\n` };
|
|
1425
|
+
const items = hqCoreDeficiencies(threadDoc);
|
|
1426
|
+
if (items.length === 0)
|
|
1427
|
+
return { code: 0, stdout: "skipped: no hq-core deficiencies\n", stderr: "" };
|
|
1428
|
+
const stateDir = path.join(root, "workspace/handoff-autofile");
|
|
1429
|
+
const ledgerPath = path.join(stateDir, "filed.json");
|
|
1430
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
1431
|
+
let ledger = {};
|
|
1432
|
+
const existing = readJsonFile(ledgerPath);
|
|
1433
|
+
if (isRecord(existing))
|
|
1434
|
+
ledger = { ...existing };
|
|
1435
|
+
else
|
|
1436
|
+
fs.writeFileSync(ledgerPath, "{}\n");
|
|
1437
|
+
const now = Math.floor(Date.now() / 1000);
|
|
1438
|
+
const fresh = items.flatMap((item) => {
|
|
1439
|
+
const hash = sha256(`${interp(item.lever)}\n${interp(item.summary)}`);
|
|
1440
|
+
const raw = ledger[hash];
|
|
1441
|
+
const filedAt = raw === undefined ? 0 : Number(raw);
|
|
1442
|
+
if (!Number.isFinite(filedAt))
|
|
1443
|
+
return [];
|
|
1444
|
+
return filedAt < now - AUTOFILE_WINDOW_SECONDS ? [{ ...item, hash }] : [];
|
|
1445
|
+
});
|
|
1446
|
+
if (fresh.length === 0)
|
|
1447
|
+
return { code: 0, stdout: "skipped: all hq-core deficiencies already filed in the last 7 days\n", stderr: "" };
|
|
1448
|
+
const ranked = [...fresh].sort((left, right) => severityRank(left) - severityRank(right));
|
|
1449
|
+
const topSummary = ranked[0] ? jqAlt(ranked[0].summary, "HQ handoff deficiencies") : "HQ handoff deficiencies";
|
|
1450
|
+
let title = jqText(topSummary);
|
|
1451
|
+
const degraded = fresh.some((item) => interp(item.severity) === "high" && IMPACT_PATTERN.test(interp(item.evidence)));
|
|
1452
|
+
const impact = degraded ? "degraded" : "inferred";
|
|
1453
|
+
if (impact === "inferred")
|
|
1454
|
+
title = `[observation] ${title}`;
|
|
1455
|
+
const systemInfo = isRecord(threadDoc) ? jqAlt(threadDoc.system_info, {}) : {};
|
|
1456
|
+
const body = autofileBody(fresh, impact, systemInfo);
|
|
1457
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "handoff-autofile-"));
|
|
1458
|
+
const bodyFile = path.join(scratch, "body");
|
|
1459
|
+
try {
|
|
1460
|
+
fs.writeFileSync(bodyFile, body);
|
|
1461
|
+
if (matchingSecretPatterns(body).length > 0) {
|
|
1462
|
+
return { code: 0, stdout: "aborted: report body matched a secret pattern; nothing submitted\n", stderr: "" };
|
|
1463
|
+
}
|
|
1464
|
+
const filed = subprocess("hq", [
|
|
1465
|
+
"feedback", "bug", "--reporter", "agent", "--title", title, "--body-file", bodyFile, "--no-logs",
|
|
1466
|
+
], context.cwd, { stdout: "capture", stderr: "pipe" });
|
|
1467
|
+
if (filed.code !== 0)
|
|
1468
|
+
return { code: 0, stdout: "failed: hq feedback bug exited non-zero\n", stderr: "" };
|
|
1469
|
+
const next = { ...ledger };
|
|
1470
|
+
for (const item of fresh)
|
|
1471
|
+
next[String(item.hash)] = now;
|
|
1472
|
+
const temporary = path.join(stateDir, `.filed.json.${process.pid}.${Math.random().toString(36).slice(2)}`);
|
|
1473
|
+
fs.writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);
|
|
1474
|
+
fs.renameSync(temporary, ledgerPath);
|
|
1475
|
+
return { code: 0, stdout: `filed: ${feedbackId(`${filed.stdout ?? ""}\n${filed.stderr ?? ""}`)}\n`, stderr: "" };
|
|
1476
|
+
}
|
|
1477
|
+
finally {
|
|
1478
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
function archiveNo(reason) {
|
|
1482
|
+
return { code: 0, stdout: `archive: no (${reason})\n`, stderr: "" };
|
|
1483
|
+
}
|
|
1484
|
+
function shellWords(text) {
|
|
1485
|
+
return text.split(/[ \t\n]+/).filter((token) => token.length > 0);
|
|
1486
|
+
}
|
|
1487
|
+
function readHandoffMessage(file) {
|
|
1488
|
+
if (!file)
|
|
1489
|
+
return { ok: true, text: "" };
|
|
1490
|
+
if (file === "-") {
|
|
1491
|
+
try {
|
|
1492
|
+
return { ok: true, text: fs.readFileSync(0, "utf8") };
|
|
1493
|
+
}
|
|
1494
|
+
catch {
|
|
1495
|
+
return { ok: false };
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
try {
|
|
1499
|
+
if (!isFile(file))
|
|
1500
|
+
return { ok: false };
|
|
1501
|
+
fs.accessSync(file, fs.constants.R_OK);
|
|
1502
|
+
return { ok: true, text: fs.readFileSync(file, "utf8") };
|
|
1503
|
+
}
|
|
1504
|
+
catch {
|
|
1505
|
+
return { ok: false };
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
function truthySetting(value) {
|
|
1509
|
+
return value === "1" || value === "true" || value === "TRUE" || value === "True"
|
|
1510
|
+
|| value === "on" || value === "ON" || value === "yes" || value === "YES";
|
|
1511
|
+
}
|
|
1512
|
+
function settingScalar(value) {
|
|
1513
|
+
if (value === null || value === undefined)
|
|
1514
|
+
return undefined;
|
|
1515
|
+
if (typeof value === "boolean")
|
|
1516
|
+
return value ? "true" : "false";
|
|
1517
|
+
if (typeof value === "number")
|
|
1518
|
+
return String(value);
|
|
1519
|
+
if (typeof value === "string" && value.trim())
|
|
1520
|
+
return value.trim();
|
|
1521
|
+
return undefined;
|
|
1522
|
+
}
|
|
1523
|
+
function readAutoArchive(file) {
|
|
1524
|
+
if (!isFile(file))
|
|
1525
|
+
return undefined;
|
|
1526
|
+
let doc;
|
|
1527
|
+
try {
|
|
1528
|
+
doc = yaml.load(fs.readFileSync(file, "utf8"));
|
|
1529
|
+
}
|
|
1530
|
+
catch {
|
|
1531
|
+
return undefined;
|
|
1532
|
+
}
|
|
1533
|
+
if (!isRecord(doc) || !Object.prototype.hasOwnProperty.call(doc, "auto_archive"))
|
|
1534
|
+
return undefined;
|
|
1535
|
+
return settingScalar(doc.auto_archive);
|
|
1536
|
+
}
|
|
1537
|
+
function realGitPath(cwd, flag) {
|
|
1538
|
+
const result = subprocess("git", ["rev-parse", flag], cwd, { stdout: "capture", stderr: "ignore" });
|
|
1539
|
+
if (result.code !== 0)
|
|
1540
|
+
return undefined;
|
|
1541
|
+
const printed = (result.stdout ?? "").trim();
|
|
1542
|
+
if (!printed)
|
|
1543
|
+
return undefined;
|
|
1544
|
+
const absolute = path.isAbsolute(printed) ? printed : path.resolve(cwd, printed);
|
|
1545
|
+
try {
|
|
1546
|
+
return fs.realpathSync(absolute);
|
|
1547
|
+
}
|
|
1548
|
+
catch {
|
|
1549
|
+
return undefined;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
function threadIsCommitted(root, threadAbs) {
|
|
1553
|
+
let rootAbs;
|
|
1554
|
+
let dirAbs;
|
|
1555
|
+
try {
|
|
1556
|
+
rootAbs = fs.realpathSync(root);
|
|
1557
|
+
dirAbs = fs.realpathSync(path.dirname(threadAbs));
|
|
1558
|
+
}
|
|
1559
|
+
catch {
|
|
1560
|
+
return false;
|
|
1561
|
+
}
|
|
1562
|
+
const absolute = path.join(dirAbs, path.basename(threadAbs));
|
|
1563
|
+
if (absolute !== rootAbs && !absolute.startsWith(`${rootAbs}${path.sep}`))
|
|
1564
|
+
return false;
|
|
1565
|
+
const relative = path.relative(rootAbs, absolute).split(path.sep).join("/");
|
|
1566
|
+
if (subprocess("git", ["rev-parse", "--git-dir"], root, { stdout: "ignore", stderr: "ignore" }).code !== 0)
|
|
1567
|
+
return false;
|
|
1568
|
+
if (subprocess("git", ["ls-files", "--error-unmatch", "--", relative], root, { stdout: "ignore", stderr: "ignore" }).code !== 0)
|
|
1569
|
+
return false;
|
|
1570
|
+
const logged = subprocess("git", ["log", "-1", "--format=%H", "--", relative], root, { stdout: "capture", stderr: "ignore" });
|
|
1571
|
+
if (logged.code !== 0 || !(logged.stdout ?? "").trim())
|
|
1572
|
+
return false;
|
|
1573
|
+
const status = subprocess("git", ["status", "--porcelain", "--", relative], root, { stdout: "capture", stderr: "ignore" });
|
|
1574
|
+
return status.code === 0 && (status.stdout ?? "").trim() === "";
|
|
1575
|
+
}
|
|
1576
|
+
function archiveSessionId(explicit, root) {
|
|
1577
|
+
if (explicit)
|
|
1578
|
+
return explicit;
|
|
1579
|
+
const fromEnv = process.env.HQ_SESSION_ID || process.env.CLAUDE_CODE_SESSION_ID || process.env.CLAUDE_SESSION_ID || "";
|
|
1580
|
+
if (fromEnv)
|
|
1581
|
+
return fromEnv;
|
|
1582
|
+
const script = path.join(root, "core/scripts/hq-session.sh");
|
|
1583
|
+
if (!isFile(script))
|
|
1584
|
+
return "";
|
|
1585
|
+
const current = subprocess("bash", [script, "current"], root, { stdout: "capture", stderr: "ignore" });
|
|
1586
|
+
return (current.stdout ?? "").replace(/\n+$/, "");
|
|
1587
|
+
}
|
|
1588
|
+
function invalidSessionId(value) {
|
|
1589
|
+
return value.startsWith(".") || /[^A-Za-z0-9._-]/.test(value);
|
|
1590
|
+
}
|
|
1591
|
+
function checkOpenPulls(dir) {
|
|
1592
|
+
if (subprocess("git", ["rev-parse", "--git-dir"], dir, { stdout: "ignore", stderr: "ignore" }).code !== 0)
|
|
1593
|
+
return undefined;
|
|
1594
|
+
const remotes = subprocess("git", ["remote"], dir, { stdout: "capture", stderr: "ignore" });
|
|
1595
|
+
if (remotes.code !== 0 || !(remotes.stdout ?? "").trim())
|
|
1596
|
+
return undefined;
|
|
1597
|
+
const head = subprocess("git", ["symbolic-ref", "--short", "-q", "HEAD"], dir, { stdout: "capture", stderr: "ignore" });
|
|
1598
|
+
if (head.code !== 0)
|
|
1599
|
+
return undefined;
|
|
1600
|
+
const branch = (head.stdout ?? "").trim();
|
|
1601
|
+
if (!branch || branch === "main" || branch === "master")
|
|
1602
|
+
return undefined;
|
|
1603
|
+
const origin = subprocess("git", ["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"], dir, { stdout: "capture", stderr: "ignore" });
|
|
1604
|
+
const remoteHead = origin.code === 0 ? (origin.stdout ?? "").trim().replace(/^origin\//, "") : "";
|
|
1605
|
+
if (remoteHead && branch === remoteHead)
|
|
1606
|
+
return undefined;
|
|
1607
|
+
const pulls = subprocess("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number,url"], dir, {
|
|
1608
|
+
stdout: "capture",
|
|
1609
|
+
stderr: "ignore",
|
|
1610
|
+
});
|
|
1611
|
+
if (pulls.code !== 0)
|
|
1612
|
+
return archiveNo(`could not verify open PRs for branch ${branch}`);
|
|
1613
|
+
let parsed;
|
|
1614
|
+
try {
|
|
1615
|
+
parsed = JSON.parse(pulls.stdout ?? "");
|
|
1616
|
+
}
|
|
1617
|
+
catch {
|
|
1618
|
+
return archiveNo(`could not verify open PRs for branch ${branch}`);
|
|
1619
|
+
}
|
|
1620
|
+
if (!Array.isArray(parsed))
|
|
1621
|
+
return archiveNo(`could not verify open PRs for branch ${branch}`);
|
|
1622
|
+
const first = parsed[0];
|
|
1623
|
+
const url = isRecord(first) ? jqAlt(first.url, "") : "";
|
|
1624
|
+
const urlText = typeof url === "string" ? url : jqText(url);
|
|
1625
|
+
if (urlText)
|
|
1626
|
+
return archiveNo(`open PR on branch ${branch}: ${urlText}`);
|
|
1627
|
+
return undefined;
|
|
1628
|
+
}
|
|
1629
|
+
const STOPPED_MONITORS = new Set(["stopped", "exited", "failed", "completed", "done", "killed", "cancelled"]);
|
|
1630
|
+
function laneCount(stdout) {
|
|
1631
|
+
let parsed;
|
|
1632
|
+
try {
|
|
1633
|
+
parsed = JSON.parse(stdout);
|
|
1634
|
+
}
|
|
1635
|
+
catch {
|
|
1636
|
+
return undefined;
|
|
1637
|
+
}
|
|
1638
|
+
if (!isRecord(parsed) || parsed.ok !== true)
|
|
1639
|
+
return undefined;
|
|
1640
|
+
if (parsed.lanes === undefined || parsed.lanes === null)
|
|
1641
|
+
return 0;
|
|
1642
|
+
return Array.isArray(parsed.lanes) ? parsed.lanes.length : undefined;
|
|
1643
|
+
}
|
|
1644
|
+
function activeMonitorId(stdout, sessionId) {
|
|
1645
|
+
let parsed;
|
|
1646
|
+
try {
|
|
1647
|
+
parsed = JSON.parse(stdout);
|
|
1648
|
+
}
|
|
1649
|
+
catch {
|
|
1650
|
+
return undefined;
|
|
1651
|
+
}
|
|
1652
|
+
if (!isRecord(parsed))
|
|
1653
|
+
return undefined;
|
|
1654
|
+
const monitors = Array.isArray(parsed.monitors) ? parsed.monitors : [];
|
|
1655
|
+
for (const monitor of monitors) {
|
|
1656
|
+
if (!isRecord(monitor))
|
|
1657
|
+
continue;
|
|
1658
|
+
const target = isRecord(monitor.target) ? monitor.target : {};
|
|
1659
|
+
const session = jqText(jqAlt(target.sessionId, jqAlt(target.session_id, "")));
|
|
1660
|
+
if (session !== sessionId)
|
|
1661
|
+
continue;
|
|
1662
|
+
const state = isRecord(monitor.state) ? monitor.state : {};
|
|
1663
|
+
const status = jqText(jqAlt(state.status, "running"));
|
|
1664
|
+
if (STOPPED_MONITORS.has(status))
|
|
1665
|
+
continue;
|
|
1666
|
+
const id = monitor.monitor_id;
|
|
1667
|
+
if (typeof id === "string" && id)
|
|
1668
|
+
return id;
|
|
1669
|
+
}
|
|
1670
|
+
return "";
|
|
1671
|
+
}
|
|
1672
|
+
function queuedAskId(file, sessionId) {
|
|
1673
|
+
const parsed = readJsonFile(file);
|
|
1674
|
+
if (parsed === undefined)
|
|
1675
|
+
return undefined;
|
|
1676
|
+
const asks = isRecord(parsed) ? jqAlt(parsed.asks, {}) : {};
|
|
1677
|
+
if (!isRecord(asks))
|
|
1678
|
+
return undefined;
|
|
1679
|
+
for (const value of Object.values(asks)) {
|
|
1680
|
+
if (!isRecord(value))
|
|
1681
|
+
continue;
|
|
1682
|
+
if (value.session === sessionId && value.status === "queued") {
|
|
1683
|
+
const id = value.ask_id;
|
|
1684
|
+
return typeof id === "string" ? id : jqText(id);
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
return "";
|
|
1688
|
+
}
|
|
1689
|
+
function jqCompare(left, right) {
|
|
1690
|
+
const rank = (value) => {
|
|
1691
|
+
if (value === null || value === undefined)
|
|
1692
|
+
return 0;
|
|
1693
|
+
if (value === false)
|
|
1694
|
+
return 1;
|
|
1695
|
+
if (value === true)
|
|
1696
|
+
return 2;
|
|
1697
|
+
if (typeof value === "number")
|
|
1698
|
+
return 3;
|
|
1699
|
+
if (typeof value === "string")
|
|
1700
|
+
return 4;
|
|
1701
|
+
if (Array.isArray(value))
|
|
1702
|
+
return 5;
|
|
1703
|
+
return 6;
|
|
1704
|
+
};
|
|
1705
|
+
const leftRank = rank(left);
|
|
1706
|
+
const rightRank = rank(right);
|
|
1707
|
+
if (leftRank !== rightRank)
|
|
1708
|
+
return leftRank - rightRank;
|
|
1709
|
+
if (typeof left === "number" && typeof right === "number")
|
|
1710
|
+
return left - right;
|
|
1711
|
+
if (typeof left === "string" && typeof right === "string")
|
|
1712
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
1713
|
+
return 0;
|
|
1714
|
+
}
|
|
1715
|
+
function decisionAskId(file, sessionId) {
|
|
1716
|
+
let text;
|
|
1717
|
+
try {
|
|
1718
|
+
text = fs.readFileSync(file, "utf8");
|
|
1719
|
+
}
|
|
1720
|
+
catch {
|
|
1721
|
+
return undefined;
|
|
1722
|
+
}
|
|
1723
|
+
const records = [];
|
|
1724
|
+
try {
|
|
1725
|
+
for (const line of text.split("\n")) {
|
|
1726
|
+
const trimmed = line.trim();
|
|
1727
|
+
if (trimmed)
|
|
1728
|
+
records.push(JSON.parse(trimmed));
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
catch {
|
|
1732
|
+
return undefined;
|
|
1733
|
+
}
|
|
1734
|
+
const indexed = records.map((raw, index) => ({ raw, index, id: isRecord(raw) ? raw.id ?? null : null }));
|
|
1735
|
+
indexed.sort((left, right) => jqCompare(left.id, right.id) || left.index - right.index);
|
|
1736
|
+
let currentKey = "";
|
|
1737
|
+
let merged;
|
|
1738
|
+
const groups = [];
|
|
1739
|
+
for (const entry of indexed) {
|
|
1740
|
+
const key = JSON.stringify(entry.id);
|
|
1741
|
+
if (!merged || key !== currentKey) {
|
|
1742
|
+
currentKey = key;
|
|
1743
|
+
merged = {};
|
|
1744
|
+
groups.push(merged);
|
|
1745
|
+
}
|
|
1746
|
+
if (isRecord(entry.raw))
|
|
1747
|
+
Object.assign(merged, entry.raw);
|
|
1748
|
+
}
|
|
1749
|
+
for (const row of groups) {
|
|
1750
|
+
const ref = typeof row.ref === "string" ? row.ref : "";
|
|
1751
|
+
if (row.source === "ask" && (row.status === "open" || row.status === "answered") && ref.startsWith(`${sessionId}:`)) {
|
|
1752
|
+
return ref.replace(/^[^:]*:/, "");
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
return "";
|
|
1756
|
+
}
|
|
1757
|
+
function conductNames(dir, suffix) {
|
|
1758
|
+
if (!isDirectory(dir))
|
|
1759
|
+
return [];
|
|
1760
|
+
return fs.readdirSync(dir).filter((name) => name.endsWith(suffix)).sort();
|
|
1761
|
+
}
|
|
1762
|
+
export function runHandoffArchiveDecision(args, context) {
|
|
1763
|
+
let hqRoot = process.env.HQ_ROOT || process.env.CLAUDE_PROJECT_DIR || context.root;
|
|
1764
|
+
let argsFile = "";
|
|
1765
|
+
let cwd = context.cwd;
|
|
1766
|
+
const repoDirs = [];
|
|
1767
|
+
let thread = "";
|
|
1768
|
+
let sessionId = "";
|
|
1769
|
+
let recoveryPending = false;
|
|
1770
|
+
let backgroundRunning = false;
|
|
1771
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1772
|
+
const token = args[index] ?? "";
|
|
1773
|
+
const next = args[index + 1];
|
|
1774
|
+
if (token === "--root") {
|
|
1775
|
+
if (next !== undefined)
|
|
1776
|
+
hqRoot = next || hqRoot;
|
|
1777
|
+
index += 1;
|
|
1778
|
+
}
|
|
1779
|
+
else if (token === "--args-file") {
|
|
1780
|
+
argsFile = next ?? "";
|
|
1781
|
+
index += 1;
|
|
1782
|
+
}
|
|
1783
|
+
else if (token === "--cwd") {
|
|
1784
|
+
if (next !== undefined)
|
|
1785
|
+
cwd = next || cwd;
|
|
1786
|
+
index += 1;
|
|
1787
|
+
}
|
|
1788
|
+
else if (token === "--repo-dir") {
|
|
1789
|
+
if (next)
|
|
1790
|
+
repoDirs.push(next);
|
|
1791
|
+
index += 1;
|
|
1792
|
+
}
|
|
1793
|
+
else if (token === "--thread") {
|
|
1794
|
+
thread = next ?? "";
|
|
1795
|
+
index += 1;
|
|
1796
|
+
}
|
|
1797
|
+
else if (token === "--session-id") {
|
|
1798
|
+
sessionId = next ?? "";
|
|
1799
|
+
index += 1;
|
|
1800
|
+
}
|
|
1801
|
+
else if (token === "--recovery-pending")
|
|
1802
|
+
recoveryPending = true;
|
|
1803
|
+
else if (token === "--background-running")
|
|
1804
|
+
backgroundRunning = true;
|
|
1805
|
+
}
|
|
1806
|
+
const message = readHandoffMessage(argsFile);
|
|
1807
|
+
if (!message.ok)
|
|
1808
|
+
return archiveNo("could not read the handoff message");
|
|
1809
|
+
let leading = true;
|
|
1810
|
+
let flagNo = false;
|
|
1811
|
+
let flagArchive = false;
|
|
1812
|
+
let flagStray = false;
|
|
1813
|
+
for (const token of shellWords(message.text)) {
|
|
1814
|
+
if (leading && !token.startsWith("-"))
|
|
1815
|
+
leading = false;
|
|
1816
|
+
if (token === "--no-archive")
|
|
1817
|
+
flagNo = true;
|
|
1818
|
+
else if (token === "--archive") {
|
|
1819
|
+
if (leading)
|
|
1820
|
+
flagArchive = true;
|
|
1821
|
+
else
|
|
1822
|
+
flagStray = true;
|
|
1823
|
+
}
|
|
1824
|
+
else if (token.includes("--archive"))
|
|
1825
|
+
flagStray = true;
|
|
1826
|
+
}
|
|
1827
|
+
let want = false;
|
|
1828
|
+
let source = "";
|
|
1829
|
+
if (flagNo)
|
|
1830
|
+
return archiveNo("--no-archive");
|
|
1831
|
+
if (flagStray)
|
|
1832
|
+
return archiveNo("--archive is not a leading flag");
|
|
1833
|
+
if (flagArchive) {
|
|
1834
|
+
want = true;
|
|
1835
|
+
source = "flag";
|
|
1836
|
+
}
|
|
1837
|
+
else if ((process.env.HQ_HANDOFF_ARCHIVE ?? "") !== "") {
|
|
1838
|
+
want = truthySetting(process.env.HQ_HANDOFF_ARCHIVE ?? "");
|
|
1839
|
+
source = "env";
|
|
1840
|
+
}
|
|
1841
|
+
else {
|
|
1842
|
+
for (const file of [path.join(hqRoot, "personal/settings/handoff.yaml"), path.join(hqRoot, "core/settings/handoff.yaml")]) {
|
|
1843
|
+
const value = readAutoArchive(file);
|
|
1844
|
+
if (value === undefined)
|
|
1845
|
+
continue;
|
|
1846
|
+
want = truthySetting(value);
|
|
1847
|
+
source = "setting";
|
|
1848
|
+
break;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
if (!want)
|
|
1852
|
+
return archiveNo(`off${source ? ` by ${source}` : ""}`);
|
|
1853
|
+
if (recoveryPending)
|
|
1854
|
+
return archiveNo("follow-up recovery pending");
|
|
1855
|
+
if (!thread)
|
|
1856
|
+
return archiveNo("handoff not verified: no --thread given");
|
|
1857
|
+
const threadAbs = path.isAbsolute(thread) ? thread : path.join(hqRoot, thread);
|
|
1858
|
+
if (!isFile(threadAbs))
|
|
1859
|
+
return archiveNo("handoff not verified: thread file missing");
|
|
1860
|
+
const threadDoc = readJsonFile(threadAbs);
|
|
1861
|
+
if (!isRecord(threadDoc))
|
|
1862
|
+
return archiveNo("handoff not verified: thread file is not valid JSON");
|
|
1863
|
+
const threadId = path.basename(threadAbs, ".json");
|
|
1864
|
+
const changeset = path.join(path.dirname(threadAbs), `${threadId}.changeset.json`);
|
|
1865
|
+
if (!isFile(changeset))
|
|
1866
|
+
return archiveNo("handoff not verified: changeset file missing");
|
|
1867
|
+
const pointerPath = path.join(hqRoot, "workspace/threads/handoff.json");
|
|
1868
|
+
if (!isFile(pointerPath))
|
|
1869
|
+
return archiveNo("handoff not verified: handoff.json missing");
|
|
1870
|
+
const resolvedSession = archiveSessionId(sessionId, hqRoot);
|
|
1871
|
+
const pointer = readJsonFile(pointerPath);
|
|
1872
|
+
const pointerMatches = isRecord(pointer) && pointer.last_thread === threadId;
|
|
1873
|
+
if (!pointerMatches) {
|
|
1874
|
+
const pointerSession = isRecord(pointer) ? jqText(jqAlt(pointer.session_id, "")) : "";
|
|
1875
|
+
const sessionMatches = resolvedSession !== "" && pointerSession === resolvedSession;
|
|
1876
|
+
if (!sessionMatches && !threadIsCommitted(hqRoot, threadAbs)) {
|
|
1877
|
+
return archiveNo("handoff not verified: handoff.json points at another thread and this thread is not committed");
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
const gitDir = realGitPath(cwd, "--git-dir");
|
|
1881
|
+
if (gitDir) {
|
|
1882
|
+
const common = realGitPath(cwd, "--git-common-dir");
|
|
1883
|
+
if (common && gitDir !== common) {
|
|
1884
|
+
const dirty = subprocess("git", ["status", "--porcelain"], cwd, { stdout: "capture", stderr: "ignore" });
|
|
1885
|
+
if ((dirty.stdout ?? "").trim())
|
|
1886
|
+
return archiveNo("uncommitted changes in this session's worktree");
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
const openOnCwd = checkOpenPulls(cwd);
|
|
1890
|
+
if (openOnCwd)
|
|
1891
|
+
return openOnCwd;
|
|
1892
|
+
for (const repo of repoDirs) {
|
|
1893
|
+
const open = checkOpenPulls(repo);
|
|
1894
|
+
if (open)
|
|
1895
|
+
return open;
|
|
1896
|
+
}
|
|
1897
|
+
if (backgroundRunning)
|
|
1898
|
+
return archiveNo("background work running in this session");
|
|
1899
|
+
if (!resolvedSession)
|
|
1900
|
+
return archiveNo("could not verify background work: no session id");
|
|
1901
|
+
if (invalidSessionId(resolvedSession))
|
|
1902
|
+
return archiveNo("could not verify background work: invalid session id");
|
|
1903
|
+
const lanes = subprocess("hq", ["lanes", "list", "--senior", `session:${resolvedSession}`, "--active", "--json"], cwd, {
|
|
1904
|
+
stdout: "capture",
|
|
1905
|
+
stderr: "ignore",
|
|
1906
|
+
env: { HQ_NO_UPDATE_CHECK: "1" },
|
|
1907
|
+
});
|
|
1908
|
+
if (lanes.code !== 0)
|
|
1909
|
+
return archiveNo("could not verify background work: hq lanes list failed");
|
|
1910
|
+
const lanesActive = laneCount(lanes.stdout ?? "");
|
|
1911
|
+
if (lanesActive === undefined)
|
|
1912
|
+
return archiveNo("could not verify background work: hq lanes list failed");
|
|
1913
|
+
if (lanesActive > 0)
|
|
1914
|
+
return archiveNo(`background work running: ${lanesActive} active lane(s)`);
|
|
1915
|
+
const monitors = subprocess("hq", ["monitor", "list", "--json"], cwd, {
|
|
1916
|
+
stdout: "capture",
|
|
1917
|
+
stderr: "ignore",
|
|
1918
|
+
env: { HQ_NO_UPDATE_CHECK: "1" },
|
|
1919
|
+
});
|
|
1920
|
+
if (monitors.code !== 0)
|
|
1921
|
+
return archiveNo("could not verify background work: hq monitor list failed");
|
|
1922
|
+
const monitorId = activeMonitorId(monitors.stdout ?? "", resolvedSession);
|
|
1923
|
+
if (monitorId === undefined)
|
|
1924
|
+
return archiveNo("could not verify background work: hq monitor list failed");
|
|
1925
|
+
if (monitorId)
|
|
1926
|
+
return archiveNo(`background work running: monitor ${monitorId}`);
|
|
1927
|
+
const conduct = path.join(hqRoot, "workspace/reports/conduct");
|
|
1928
|
+
if (isDirectory(conduct)) {
|
|
1929
|
+
for (const name of conductNames(conduct, "-asks.json")) {
|
|
1930
|
+
const ask = queuedAskId(path.join(conduct, name), resolvedSession);
|
|
1931
|
+
if (ask === undefined)
|
|
1932
|
+
return archiveNo(`could not verify pending asks: ${name}`);
|
|
1933
|
+
if (ask)
|
|
1934
|
+
return archiveNo(`pending ask waiting on the owner: ${ask}`);
|
|
1935
|
+
}
|
|
1936
|
+
for (const name of conductNames(conduct, "-decisions.jsonl")) {
|
|
1937
|
+
const ask = decisionAskId(path.join(conduct, name), resolvedSession);
|
|
1938
|
+
if (ask === undefined)
|
|
1939
|
+
return archiveNo(`could not verify pending asks: ${name}`);
|
|
1940
|
+
if (ask)
|
|
1941
|
+
return archiveNo(`pending ask waiting on the owner: ${ask}`);
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
return { code: 0, stdout: "archive: yes\n", stderr: "" };
|
|
1945
|
+
}
|
|
1946
|
+
const HANDOFF_RUN_USAGE = "Usage: hq core handoff run --files-touched-json-file <path> [--learnings-file <path>] [--no-post] [--no-autofile] [--no-builder-route] [finalize args...]\n";
|
|
1947
|
+
function parsedOrText(stdout) {
|
|
1948
|
+
const trimmed = stdout.trim();
|
|
1949
|
+
if (!trimmed)
|
|
1950
|
+
return "";
|
|
1951
|
+
try {
|
|
1952
|
+
return JSON.parse(trimmed);
|
|
1953
|
+
}
|
|
1954
|
+
catch {
|
|
1955
|
+
return trimmed;
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
function handoffFlowResult(code, payload, knowledge, post, autofile, builderRoute, builderBrief, stderr) {
|
|
1959
|
+
return {
|
|
1960
|
+
code,
|
|
1961
|
+
stdout: compactJson({
|
|
1962
|
+
...payload,
|
|
1963
|
+
knowledge_commit: { code: knowledge.code, result: parsedOrText(knowledge.stdout) },
|
|
1964
|
+
post,
|
|
1965
|
+
autofile,
|
|
1966
|
+
builder_route: builderRoute,
|
|
1967
|
+
builder_brief: builderBrief,
|
|
1968
|
+
}),
|
|
1969
|
+
stderr,
|
|
1970
|
+
};
|
|
1971
|
+
}
|
|
1972
|
+
export async function runHandoffFlow(args, context) {
|
|
1973
|
+
let learningsFile;
|
|
1974
|
+
let filesFile = "";
|
|
1975
|
+
let sawFilesFile = false;
|
|
1976
|
+
let noPost = false;
|
|
1977
|
+
let noAutofile = false;
|
|
1978
|
+
let noBuilder = false;
|
|
1979
|
+
const finalizeArgs = [];
|
|
1980
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1981
|
+
const token = args[index] ?? "";
|
|
1982
|
+
if (token === "--no-post") {
|
|
1983
|
+
noPost = true;
|
|
1984
|
+
continue;
|
|
1985
|
+
}
|
|
1986
|
+
if (token === "--no-autofile") {
|
|
1987
|
+
noAutofile = true;
|
|
1988
|
+
continue;
|
|
1989
|
+
}
|
|
1990
|
+
if (token === "--no-builder-route") {
|
|
1991
|
+
noBuilder = true;
|
|
1992
|
+
continue;
|
|
1993
|
+
}
|
|
1994
|
+
if (token === "--learnings-file") {
|
|
1995
|
+
learningsFile = args[index + 1] ?? "";
|
|
1996
|
+
index += 1;
|
|
1997
|
+
continue;
|
|
1998
|
+
}
|
|
1999
|
+
if (token === "--files-touched-json-file") {
|
|
2000
|
+
sawFilesFile = true;
|
|
2001
|
+
filesFile = args[index + 1] ?? "";
|
|
2002
|
+
finalizeArgs.push(token, filesFile);
|
|
2003
|
+
index += 1;
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
2006
|
+
finalizeArgs.push(token);
|
|
2007
|
+
}
|
|
2008
|
+
if (!sawFilesFile || !filesFile)
|
|
2009
|
+
return { code: 2, stdout: "", stderr: HANDOFF_RUN_USAGE };
|
|
2010
|
+
const knowledge = runHandoffKnowledgeCommit(["--files-touched-json-file", filesFile], context.root);
|
|
2011
|
+
if (knowledge.code !== 0)
|
|
2012
|
+
return { code: knowledge.code, stdout: "", stderr: `${knowledge.stdout}${knowledge.stderr}` };
|
|
2013
|
+
let stderr = knowledge.stderr;
|
|
2014
|
+
const finalized = runHandoffFinalize(finalizeArgs, context);
|
|
2015
|
+
stderr += finalized.stderr;
|
|
2016
|
+
let payload;
|
|
2017
|
+
if (finalized.stdout.trim()) {
|
|
2018
|
+
try {
|
|
2019
|
+
const parsed = JSON.parse(finalized.stdout);
|
|
2020
|
+
if (isRecord(parsed))
|
|
2021
|
+
payload = parsed;
|
|
2022
|
+
}
|
|
2023
|
+
catch {
|
|
2024
|
+
payload = undefined;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
const idlePost = (skipped) => ({ launched: false, skipped, error: null });
|
|
2028
|
+
if (finalized.code !== 0 || !payload) {
|
|
2029
|
+
if (payload) {
|
|
2030
|
+
return handoffFlowResult(finalized.code, payload, knowledge, idlePost(noPost), null, null, null, stderr);
|
|
2031
|
+
}
|
|
2032
|
+
return { code: finalized.code || 1, stdout: "", stderr: `${stderr}${finalized.stdout}` };
|
|
2033
|
+
}
|
|
2034
|
+
const threadPath = typeof payload.thread_path === "string" ? payload.thread_path : "";
|
|
2035
|
+
let post = idlePost(noPost);
|
|
2036
|
+
if (!noPost) {
|
|
2037
|
+
const posted = await Promise.resolve(runHandoffPost([threadPath, learningsFile ?? ""], context));
|
|
2038
|
+
stderr += posted.stdout;
|
|
2039
|
+
stderr += posted.stderr;
|
|
2040
|
+
post = posted.code === 0
|
|
2041
|
+
? { launched: true, skipped: false, error: null }
|
|
2042
|
+
: { launched: false, skipped: false, error: (posted.stderr || posted.stdout || `exit ${posted.code}`).trim() || `exit ${posted.code}` };
|
|
2043
|
+
}
|
|
2044
|
+
let autofile = null;
|
|
2045
|
+
if (!noAutofile) {
|
|
2046
|
+
const filed = runHandoffAutofile(["--thread", threadPath, "--root", context.root], context);
|
|
2047
|
+
stderr += filed.stderr;
|
|
2048
|
+
autofile = filed.stdout.replace(/\n+$/, "") || null;
|
|
2049
|
+
if (filed.code !== 0)
|
|
2050
|
+
return handoffFlowResult(filed.code, payload, knowledge, post, autofile, null, null, stderr);
|
|
2051
|
+
}
|
|
2052
|
+
let builderRoute = null;
|
|
2053
|
+
let builderBrief = null;
|
|
2054
|
+
if (!noBuilder) {
|
|
2055
|
+
const routed = runHandoffBuilderRoute(["--root", context.root, "--thread", threadPath], context);
|
|
2056
|
+
stderr += routed.stderr;
|
|
2057
|
+
const lines = routed.stdout.split("\n").filter((line) => line.length > 0);
|
|
2058
|
+
builderRoute = lines.find((line) => line.startsWith("route:")) ?? null;
|
|
2059
|
+
builderBrief = lines.find((line) => line.startsWith("brief:")) ?? null;
|
|
2060
|
+
if (routed.code !== 0)
|
|
2061
|
+
return handoffFlowResult(routed.code, payload, knowledge, post, autofile, builderRoute, builderBrief, stderr);
|
|
2062
|
+
}
|
|
2063
|
+
return handoffFlowResult(0, payload, knowledge, post, autofile, builderRoute, builderBrief, stderr);
|
|
2064
|
+
}
|
|
1113
2065
|
function withRootEnvironment(root, action) {
|
|
1114
2066
|
const saved = new Map();
|
|
1115
2067
|
for (const key of ["HQ_ROOT", "CLAUDE_PROJECT_DIR", "PWD"])
|
|
@@ -1117,16 +2069,24 @@ function withRootEnvironment(root, action) {
|
|
|
1117
2069
|
process.env.HQ_ROOT = root;
|
|
1118
2070
|
process.env.CLAUDE_PROJECT_DIR = root;
|
|
1119
2071
|
process.env.PWD = root;
|
|
1120
|
-
|
|
1121
|
-
return action();
|
|
1122
|
-
}
|
|
1123
|
-
finally {
|
|
2072
|
+
const restore = () => {
|
|
1124
2073
|
for (const [key, value] of saved) {
|
|
1125
2074
|
if (value === undefined)
|
|
1126
2075
|
delete process.env[key];
|
|
1127
2076
|
else
|
|
1128
2077
|
process.env[key] = value;
|
|
1129
2078
|
}
|
|
2079
|
+
};
|
|
2080
|
+
try {
|
|
2081
|
+
const result = action();
|
|
2082
|
+
if (result instanceof Promise)
|
|
2083
|
+
return result.finally(restore);
|
|
2084
|
+
restore();
|
|
2085
|
+
return result;
|
|
2086
|
+
}
|
|
2087
|
+
catch (error) {
|
|
2088
|
+
restore();
|
|
2089
|
+
throw error;
|
|
1130
2090
|
}
|
|
1131
2091
|
}
|
|
1132
2092
|
function emitResult(result) {
|
|
@@ -1156,6 +2116,13 @@ export async function runHandoffFast(args, _stdin, _cwd, hqRoot, commandName) {
|
|
|
1156
2116
|
process.exitCode = result.code;
|
|
1157
2117
|
return result.code;
|
|
1158
2118
|
}
|
|
2119
|
+
const NATIVE_HANDOFF_COMMANDS = [
|
|
2120
|
+
["pointer-company", "Print the single company slug from the latest handoff"],
|
|
2121
|
+
["builder-route", "Choose the handoff builder or public route"],
|
|
2122
|
+
["autofile", "File one feedback report for hq-core handoff deficiencies"],
|
|
2123
|
+
["archive-decision", "Decide whether the handoff session should be archived"],
|
|
2124
|
+
["run", "Run the mechanical handoff steps"],
|
|
2125
|
+
];
|
|
1159
2126
|
/** Register native handoff commands behind the shared default-off flag. */
|
|
1160
2127
|
export function registerCoreHandoffCommand(core) {
|
|
1161
2128
|
const handoff = core.command("handoff").description("Handoff session helpers");
|
|
@@ -1191,5 +2158,32 @@ export function registerCoreHandoffCommand(core) {
|
|
|
1191
2158
|
const asset = ASSETS[name === "open-steps" ? "openSteps" : name];
|
|
1192
2159
|
describeCoreCommand(command, { execution: "native", asset, root: "live" });
|
|
1193
2160
|
}
|
|
2161
|
+
for (const [name, description] of NATIVE_HANDOFF_COMMANDS) {
|
|
2162
|
+
const command = handoff.command(name)
|
|
2163
|
+
.description(description)
|
|
2164
|
+
.allowUnknownOption()
|
|
2165
|
+
.allowExcessArguments()
|
|
2166
|
+
.helpOption(false)
|
|
2167
|
+
.argument("[args...]", "arguments accepted for shell ABI compatibility")
|
|
2168
|
+
.action(async (args = [], _options, cmd) => {
|
|
2169
|
+
const scope = core.opts();
|
|
2170
|
+
const root = resolveLiveRoot({ hqRoot: scope.hqRoot });
|
|
2171
|
+
const operands = cmd.args.length > 0 ? cmd.args : args;
|
|
2172
|
+
const result = await withRootEnvironment(root, () => {
|
|
2173
|
+
const context = { root, cwd: root };
|
|
2174
|
+
if (name === "pointer-company")
|
|
2175
|
+
return runHandoffPointerCompany(operands, context);
|
|
2176
|
+
if (name === "builder-route")
|
|
2177
|
+
return runHandoffBuilderRoute(operands, context);
|
|
2178
|
+
if (name === "autofile")
|
|
2179
|
+
return runHandoffAutofile(operands, context);
|
|
2180
|
+
if (name === "archive-decision")
|
|
2181
|
+
return runHandoffArchiveDecision(operands, context);
|
|
2182
|
+
return runHandoffFlow(operands, context);
|
|
2183
|
+
});
|
|
2184
|
+
emitResult(result);
|
|
2185
|
+
});
|
|
2186
|
+
describeCoreCommand(command, { execution: "native", root: "live" });
|
|
2187
|
+
}
|
|
1194
2188
|
}
|
|
1195
2189
|
//# sourceMappingURL=core-handoff.js.map
|