@nurix/nustack 0.23.9 → 0.23.11

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.
@@ -0,0 +1,48 @@
1
+ import { attributeTranscript } from "../lib/census/attribute.js";
2
+ import { CensusAccumulator, renderCensusText } from "../lib/census/report.js";
3
+ import { discoverSessions, readLines } from "../lib/census/transcripts.js";
4
+ import { printJsonSuccess } from "../lib/json_output.js";
5
+ class CensusArgumentError extends Error {
6
+ code = "CENSUS_ARGUMENT_INVALID";
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "CensusArgumentError";
10
+ }
11
+ }
12
+ function parseSince(value) {
13
+ if (value === undefined)
14
+ return undefined;
15
+ const instant = /^\d{4}-\d{2}-\d{2}$/.test(value) ? Date.parse(`${value}T00:00:00Z`) : Number.NaN;
16
+ if (Number.isNaN(instant))
17
+ throw new CensusArgumentError(`--since takes a date as YYYY-MM-DD, not "${value}".`);
18
+ return instant;
19
+ }
20
+ function parseMaxSessions(value) {
21
+ if (value === undefined)
22
+ return undefined;
23
+ if (!/^\d+$/.test(value) || Number.parseInt(value, 10) < 1) {
24
+ throw new CensusArgumentError(`--max-sessions takes a positive integer, not "${value}".`);
25
+ }
26
+ return Number.parseInt(value, 10);
27
+ }
28
+ export async function runCensus(options) {
29
+ const sessions = await discoverSessions({
30
+ root: options.root,
31
+ sinceMs: parseSince(options.since),
32
+ maxSessions: parseMaxSessions(options.maxSessions),
33
+ });
34
+ const census = new CensusAccumulator();
35
+ for (const session of sessions) {
36
+ census.addSession();
37
+ census.addTranscript(await attributeTranscript(readLines(session.mainPath), "main"), "main");
38
+ for (const sidechainPath of session.sidechainPaths) {
39
+ census.addTranscript(await attributeTranscript(readLines(sidechainPath), "sidechain"), "sidechain");
40
+ }
41
+ }
42
+ const report = census.finish();
43
+ if (options.json) {
44
+ printJsonSuccess("census", report);
45
+ return;
46
+ }
47
+ console.log(renderCensusText(report));
48
+ }
@@ -0,0 +1,75 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { hasManagedHook, installManagedHook, removeManagedHook } from "../lib/agent/claudeHooks.js";
4
+ import { readDesktopSettings } from "../lib/desktop_settings.js";
5
+ import { loadOutlineLibrary } from "../lib/gate/outline.js";
6
+ import { resolveThreshold } from "../lib/gate/settings.js";
7
+ import { printJsonSuccess } from "../lib/json_output.js";
8
+ import { readStoreVersion } from "../lib/local_store/database.js";
9
+ export const GATE_HOOK_TIMEOUT_SECONDS = 10;
10
+ export const GATE_HOOKS = [
11
+ { matcher: "Read", command: "nustack gate read" },
12
+ { matcher: "Bash", command: "nustack gate bash" },
13
+ ];
14
+ const GATE_EVENT = "PreToolUse";
15
+ function claudeSettingsPath() {
16
+ return path.join(os.homedir(), ".claude", "settings.json");
17
+ }
18
+ export async function runGateInstall() {
19
+ let isChanged = false;
20
+ for (const hook of GATE_HOOKS) {
21
+ const { changed } = await installManagedHook(claudeSettingsPath(), GATE_EVENT, hook.matcher, hook.command, {
22
+ timeout: GATE_HOOK_TIMEOUT_SECONDS,
23
+ });
24
+ isChanged ||= changed;
25
+ }
26
+ console.log(isChanged
27
+ ? "Installed the large-read gate's Read and Bash hooks."
28
+ : "Installed the large-read gate's Read and Bash hooks (already installed — no change).");
29
+ }
30
+ export async function runGateRemove() {
31
+ let isRemoved = false;
32
+ for (const hook of GATE_HOOKS) {
33
+ const { removed } = await removeManagedHook(claudeSettingsPath(), GATE_EVENT, hook.matcher);
34
+ isRemoved ||= removed;
35
+ }
36
+ console.log(isRemoved
37
+ ? "Removed the large-read gate's Read and Bash hooks."
38
+ : "Removed the large-read gate's Read and Bash hooks (already absent — no change).");
39
+ }
40
+ export async function readGateStatus() {
41
+ const settingsPath = claudeSettingsPath();
42
+ const installed = {
43
+ read: await hasManagedHook(settingsPath, GATE_EVENT, "Read"),
44
+ bash: await hasManagedHook(settingsPath, GATE_EVENT, "Bash"),
45
+ };
46
+ const { localReader } = readDesktopSettings().routing;
47
+ const isInstalled = installed.read && installed.bash;
48
+ const isUninstalled = !installed.read && !installed.bash;
49
+ const { thresholdTokens, thresholdSource } = resolveThreshold();
50
+ const library = await loadOutlineLibrary();
51
+ return {
52
+ installed,
53
+ localReader,
54
+ isInSync: localReader ? isInstalled : isUninstalled,
55
+ thresholdTokens,
56
+ thresholdSource,
57
+ outline: library !== null && typeof library.outlineSource === "function" ? "tree-sitter" : "fallback",
58
+ storeVersion: await readStoreVersion(),
59
+ };
60
+ }
61
+ export async function runGateStatus(options) {
62
+ const status = await readGateStatus();
63
+ if (options.json) {
64
+ printJsonSuccess("gate status", status);
65
+ return;
66
+ }
67
+ const onOff = (isOn) => (isOn ? "installed" : "not installed");
68
+ console.log([
69
+ `Read hook: ${onOff(status.installed.read)} · Bash hook: ${onOff(status.installed.bash)}`,
70
+ `Local Reader switch: ${status.localReader ? "on" : "off"} (${status.isInSync ? "in sync with the hooks" : "out of sync with the hooks — run `nustack gate install` or `nustack gate remove`"})`,
71
+ `Threshold: ${status.thresholdTokens} tokens (from ${status.thresholdSource})`,
72
+ `Outline: ${status.outline}`,
73
+ `Local store version: ${status.storeVersion ?? "no store"}`,
74
+ ].join("\n"));
75
+ }
package/dist/index.js CHANGED
@@ -1,458 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
3
- import { Command } from "commander";
4
- import { runLogin } from "./commands/login.js";
5
- import { runInit } from "./commands/init.js";
6
- import { runAdd } from "./commands/add.js";
7
- import { runList } from "./commands/list.js";
8
- import { runSync } from "./commands/sync.js";
9
- import { runDescribe } from "./commands/describe.js";
10
- import { runValidate } from "./commands/validate.js";
11
- import { runGraph } from "./commands/graph.js";
12
- import { runLogscope } from "./commands/logscope.js";
13
- import { runDoctor } from "./commands/doctor.js";
14
- import { runTokenCreate, runTokenList, runTokenRevoke } from "./commands/token.js";
15
- import { runOpen } from "./commands/open.js";
16
- import { runBootstrap } from "./commands/bootstrap.js";
17
- import { runLogout } from "./commands/logout.js";
18
- import { runTelemetry } from "./commands/telemetry.js";
19
- import { runSearch, runSearchServices } from "./commands/search.js";
20
- import { runDeviceList, runDeviceRevoke, runDeviceStatus } from "./commands/device.js";
21
- import { registerProjectSyncCommands } from "./commands/project-sync.js";
22
- import { registerProjectCommands } from "./commands/project.js";
23
- import { registerDeployCommands, registerLogsCommand, registerProjectSetCommand } from "./commands/deploy.js";
24
- import { registerActivityCommand } from "./commands/activity.js";
25
- import { registerWhoamiCommand } from "./commands/whoami.js";
26
- import { registerApiCommand } from "./commands/api.js";
27
- import { registerMcpCommands } from "./commands/mcp.js";
28
- import { NON_INTERACTIVE_VARIABLE } from "./lib/interactive.js";
29
- import { runOrganizationList, runOrganizationCreate, runOrganizationUse } from "./commands/organization.js";
30
- import { runDocsList, runDocsShow, runDocsStatus } from "./commands/docs.js";
31
- import { runHandoffList, runHandoffShow } from "./commands/handoff.js";
32
- import { runToolkitStatus, runToolkitReconcile } from "./commands/toolkit.js";
33
- import { runHarnessMount, runHarnessStatus } from "./commands/harness.js";
34
- import { runSessionsList, runSessionsPrune, runSessionsRecord, runSessionsServe, } from "./commands/sessions.js";
35
- import { registerReviewCommands } from "./commands/review.js";
36
- import { registerRecordsCommands, startDrainIfDue } from "./commands/records.js";
37
- import { isPartCheckStale, startTelemetryReconcile } from "./lib/telemetry/part_state.js";
38
- import { RECORD_ALIAS_GROUPS, registerRecordAliases } from "./commands/recordAliases.js";
39
- import { runAgentContext, runAgentHookInstall, runAgentHookRemove } from "./commands/agent.js";
40
- import { printJsonError } from "./lib/json_output.js";
41
- import { setCliVersion } from "./lib/auth_grant.js";
42
- const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
43
- setCliVersion(version);
44
- const program = new Command();
45
- program
46
- .name("nustack")
47
- .description("Bootstrap NuStack services into your repo via the NuStack discovery plane.")
48
- .version(version)
49
- .option("--nustack-url <url>", "NuStack base URL (defaults to $NUSTACK_URL, then the hosted instance)")
50
- .option("--non-interactive", `never prompt — take the default or refuse with a coded error (also $${NON_INTERACTIVE_VARIABLE}=1)`)
51
- .action(async () => runBootstrap(program.opts()));
52
- program.addHelpText("after", "\nRun `nustack` with no command to bootstrap: it checks your sign-in, runs login if needed, then init.");
53
- program
54
- .command("login")
55
- .description("Sign in with your browser; this machine's grant is saved to your OS keychain")
56
- .option("--no-open", "don't auto-open the browser; just print the sign-in URL")
57
- .option("--manual", "sign in anywhere and paste the code here instead of using a browser on this machine")
58
- .option("--force", "sign in again even if this machine is already signed in")
59
- .action(async (options) => runLogin(program.opts(), options));
60
- program
61
- .command("logout")
62
- .description("Sign out: end this machine's grant and clear the shared keychain credential (both CLI and desktop)")
63
- .option("--forget-device", "also clear the shared ~/.nustack/device_id machine identity")
64
- .action(async (options) => runLogout(program.opts(), { forgetDevice: options.forgetDevice }));
65
- program
66
- .command("init")
67
- .description("Onboard this folder: sign in, then bind it to a Project (the onboarding router)")
68
- .option("--organization <id>", "the Organization to create or select the Project in")
69
- .option("--yes", "pre-confirm the populated-folder onboarding guard")
70
- .action(async (options) => runInit({ ...program.opts(), ...options }));
71
- program
72
- .command("add [service]")
73
- .description("Record a stack service in this repo: install its package, add the consumes edge")
74
- .option("--json", "emit the versioned machine envelope instead of interactive output")
75
- .option("--yes", "assume yes for the package-install and manifest-scaffold prompts")
76
- .action(async (service, options) => runAdd(service, { ...program.opts(), ...options }));
77
- program
78
- .command("list")
79
- .description("List the services in the NuStack catalogue")
80
- .option("--json", "emit the versioned machine envelope wrapping the catalogue entries")
81
- .action(async (options) => runList(options, program.opts()));
82
- program
83
- .command("sync")
84
- .description("Project this Project's Service credentials into the managed .env block (not Documents or Git)")
85
- .option("--project <id>", "the Project to act as (defaults to nustack.service.json / NUSTACK_WORKSPACE_ID)")
86
- .option("--json", "emit the versioned machine envelope instead of interactive output")
87
- .action(async (options) => runSync({ ...program.opts(), ...options }));
88
- program
89
- .command("describe <service>")
90
- .description("Show the full catalogue entry for a service")
91
- .option("--json", "emit the raw catalogue entry as JSON")
92
- .action(async (service, options) => runDescribe(service, options, program.opts()));
93
- program
94
- .command("validate [manifest]")
95
- .description("Validate an nustack.service.json (path or URL) against the nustack.dev/v1 schema")
96
- .option("--schema <pathOrUrl>", "override the bundled packages/contracts/spec/schema.json")
97
- .option("--json", "emit the versioned machine envelope with { target, isValid, errors }")
98
- .action(async (manifest, options) => runValidate(manifest, options));
99
- program
100
- .command("graph [fn] [args...]")
101
- .description("The code graph: ask a question of this repository's index, or `index` / `status` / `functions`")
102
- .option("--repo <pathOrId>", "the repository to ask about (default: the working tree's root)")
103
- .option("--no-refresh", "answer from the index as it stands, however old")
104
- .option("--budget <n>", "token ceiling for the answer; 0 means unbounded")
105
- .option("--commits <n>", "history depth for `graph index` (default 5000)")
106
- .option("--json", "emit the versioned machine envelope with the answer as data")
107
- .allowUnknownOption()
108
- .allowExcessArguments()
109
- .action(async (_fn, _args, options) => runGraph(process.argv, options));
110
- program
111
- .command("logscope [fn] [args...]")
112
- .description("Log tracking: ask this machine's log corpus a question, or `index` / `corpora` / `allow` / `prune`")
113
- .option("--root <dir>", "the project this command is about (default: the working tree's root)")
114
- .option("--corpus <ref>", "a corpus id, or a path belonging to one")
115
- .option("--budget <n>", "token ceiling for the answer; 0 means unbounded")
116
- .option("--limit <n>", "rows requested — beats a default budget, never an explicit one")
117
- .option("--retain <days>", "retention for `index`; 0 keeps the corpus until it is forgotten")
118
- .option("--examples", "keep up to three exemplar log lines per template (off by default)")
119
- .option("--no-redact", "store exemplars unredacted (loud, recorded on the corpus)")
120
- .option("--since <ts>", "window start for container sources")
121
- .option("--until <ts>", "window end for container sources")
122
- .option("--revision <sha>", "the source revision these logs were written by")
123
- .option("--note <text>", "a note recorded with an `allow` grant")
124
- .option("--dry-run", "for `prune`: report what would be dropped and delete nothing")
125
- .option("--json", "emit the versioned machine envelope with the answer as data")
126
- .allowUnknownOption()
127
- .allowExcessArguments()
128
- .action(async (_fn, _args, options) => runLogscope(process.argv, options));
129
- program
130
- .command("doctor")
131
- .description("Run the full local diagnostics matrix (identity, repository, manifests, toolkit, telemetry, credentials)")
132
- .option("--project <id>", "the Project to diagnose (defaults to the bound repository)")
133
- .option("--json", "emit the versioned machine envelope (secrets and absolute paths redacted)")
134
- .option("--local-verbose", "include Device-local absolute paths in the output")
135
- .action(async (options) => runDoctor({ ...program.opts(), ...options }));
136
- registerDeployCommands(program, () => program.opts());
137
- registerLogsCommand(program, () => program.opts());
138
- registerWhoamiCommand(program, () => program.opts());
139
- registerApiCommand(program, () => program.opts());
140
- registerMcpCommands(program, () => program.opts());
141
- program
142
- .command("open <service>")
143
- .description("Open the service's dev endpoint (or repository) in the browser")
144
- .option("--env <name>", "pick a specific endpoint environment (default: dev)")
145
- .option("--json", "print the resolved URL as the machine envelope instead of launching")
146
- .action(async (service, options) => runOpen(service, options, program.opts()));
147
- const token = program.command("token").description("Mint, list and revoke your personal access tokens (the NUSTACK_TOKEN a pipeline or agent uses)");
148
- token
149
- .command("create")
150
- .description("Mint a personal access token; the secret is printed once, on stdout alone")
151
- .requiredOption("--label <label>", "a name for the token, unique among your live ones")
152
- .option("--expires <days>", "days until the token expires (1–365); no expiry when omitted")
153
- .option("--json", "emit the versioned machine envelope")
154
- .action(async (options) => runTokenCreate(options, program.opts()));
155
- token
156
- .command("list")
157
- .description("List your personal access tokens (never a secret)")
158
- .option("--json", "emit the versioned machine envelope")
159
- .action(async (options) => runTokenList(options, program.opts()));
160
- token
161
- .command("revoke <token-id>")
162
- .description("Revoke a personal access token; it stops working on the next request")
163
- .option("--json", "emit the versioned machine envelope")
164
- .action(async (tokenId, options) => runTokenRevoke(tokenId, options, program.opts()));
165
- const device = program.command("device").description("Inspect your signed-in devices and end this machine's access");
166
- device
167
- .command("list")
168
- .description("List your signed-in devices (never a token)")
169
- .option("--json", "emit the versioned machine envelope")
170
- .action(async (options) => runDeviceList(options, program.opts()));
171
- device
172
- .command("status")
173
- .description("Show this device's local state merged with its server record")
174
- .option("--json", "emit the versioned machine envelope")
175
- .action(async (options) => runDeviceStatus(options, program.opts()));
176
- device
177
- .command("revoke [device-id]")
178
- .description("End this machine's access (other machines are revoked from Profile › Devices)")
179
- .option("--json", "emit the versioned machine envelope")
180
- .option("--yes", "skip the confirmation prompt")
181
- .action(async (deviceId, options) => runDeviceRevoke(deviceId, options, program.opts()));
182
- program
183
- .command("telemetry [action]")
184
- .description("Inspect or control telemetry (status | enable | disable | reinstall | output | reconcile). Inside a bound folder, enable/disable move that folder alone; output points the shipper at your own Elastic, its key read from NUSTACK_ELASTIC_API_KEY; reconcile asks the server for each project's telemetry part")
185
- .option("--json", "emit the versioned machine envelope")
186
- .option("--device", "move this machine's switch instead of the current folder's")
187
- .option("--local-verbose", "include each folder's absolute path (local consumers only — never pipe into a log)")
188
- .option("--elastic-url <url>", "output: the Elastic endpoint (default NUSTACK_ELASTIC_URL)")
189
- .option("--index <name>", "output: the index events are written to (default claude-sessions)")
190
- .option("--quiet", "reconcile: print nothing")
191
- .action(async (action, options) => {
192
- const allowed = ["status", "enable", "disable", "reinstall", "output", "reconcile"];
193
- const chosen = (allowed.includes(action ?? "") ? action : "status");
194
- return runTelemetry(chosen, {
195
- ...program.opts(),
196
- json: options.json,
197
- device: options.device,
198
- localVerbose: options.localVerbose,
199
- elasticUrl: options.elasticUrl,
200
- index: options.index,
201
- quiet: options.quiet,
202
- });
203
- });
204
- const toLimit = (value) => Number.parseInt(value, 10);
205
- const search = program
206
- .command("search [keywords...]")
207
- .description("Search the NuStack Directory for projects by keyword")
208
- .option("--json", "emit the raw results array as JSON")
209
- .option("--category <cat>", "filter projects by category")
210
- .option("--limit <n>", "max results (default 20)", toLimit)
211
- .action(async (keywords, options) => runSearch(keywords, options, program.opts()));
212
- search
213
- .command("services [keywords...]")
214
- .description("Search the services registry by keyword (then `nustack add <name>` to integrate)")
215
- .option("--json", "emit the raw results array as JSON")
216
- .option("--type <type>", "filter services by type")
217
- .option("--limit <n>", "max results (default 20)", toLimit)
218
- .action(async (keywords, options) => runSearchServices(keywords, { ...search.opts(), ...options }, program.opts()));
219
- search.addHelpText("after", '\n`services` is a reserved subcommand. To search projects for the literal word "services", use the\n' +
220
- "explicit separator: `nustack search -- services` (everything after `--` is an projects query).");
221
- const organization = program.command("organization").description("Work with your NuStack Organizations");
222
- organization
223
- .command("list")
224
- .description("List your Organization memberships (name, slug, role, active marker)")
225
- .option("--json", "emit the versioned machine envelope")
226
- .action(async (options) => runOrganizationList(options, program.opts()));
227
- organization
228
- .command("create <name>")
229
- .description("Create an Organization and print it")
230
- .option("--json", "emit the versioned machine envelope")
231
- .action(async (name, options) => runOrganizationCreate(name, options, program.opts()));
232
- organization
233
- .command("use <id-or-slug>")
234
- .description("Set the active Organization context for this device")
235
- .option("--json", "emit the versioned machine envelope")
236
- .action(async (target, options) => runOrganizationUse(target, options, program.opts()));
237
- const project = program.command("project").description("Work with NuStack Projects");
238
- registerProjectCommands(project, () => program.opts());
239
- registerProjectSetCommand(project, () => program.opts());
240
- registerActivityCommand(project, () => program.opts());
241
- registerProjectSyncCommands(project, () => program.opts());
242
- registerReviewCommands(program.command("review").description("Read and mirror NuStack Review items"), () => program.opts());
243
- registerRecordsCommands(program.command("records").description("Emit, send and list harness records"), () => program.opts());
244
- registerRecordAliases(program, () => program.opts());
245
- program.hook("preAction", async (_program, action) => {
246
- if (program.opts().nonInteractive)
247
- process.env[NON_INTERACTIVE_VARIABLE] = "1";
248
- const group = action.parent?.name() ?? "";
249
- if (group !== "records" && !RECORD_ALIAS_GROUPS.includes(group))
250
- await startDrainIfDue(program.opts());
251
- if (action.name() !== "telemetry" && isPartCheckStale())
252
- startTelemetryReconcile({ nustackUrl: program.opts().nustackUrl });
253
- });
254
- const docs = program.command("docs").description("Work with a Project's Documents");
255
- docs
256
- .command("list")
257
- .description("List the Project's Documents")
258
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
259
- .option("--json", "emit the versioned machine envelope")
260
- .action(async (options) => runDocsList(options, program.opts()));
261
- docs
262
- .command("show <slug-or-id>")
263
- .description("Show a Document: a bounded inline body or its content URL")
264
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
265
- .option("--json", "emit the versioned machine envelope")
266
- .action(async (target, options) => runDocsShow(target, options, program.opts()));
267
- docs
268
- .command("status")
269
- .description("Report per-path local/cloud Document convergence for the bound repository")
270
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
271
- .option("--json", "emit the versioned machine envelope")
272
- .action(async (options) => runDocsStatus(options, program.opts()));
273
- const handoff = program.command("handoff").description("Work with a Project's Handoffs");
274
- handoff
275
- .command("list")
276
- .description("List the Project's Handoffs")
277
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
278
- .option("--json", "emit the versioned machine envelope")
279
- .action(async (options) => runHandoffList(options, program.opts()));
280
- handoff
281
- .command("show <id>")
282
- .description("Show a Handoff (add --targets for the binding-scoped per-target manifest)")
283
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
284
- .option("--targets", "list each target's path, operation, and base semantics")
285
- .option("--json", "emit the versioned machine envelope")
286
- .action(async (id, options) => runHandoffShow(id, options, program.opts()));
287
- const sessions = program
288
- .command("sessions")
289
- .description("Sessions on this machine — the engine the desktop drives, and the record of what ran");
290
- sessions
291
- .command("serve")
292
- .description("Run the long-lived session supervisor: JSONL frames on stdin/stdout (used by the NuStack desktop)")
293
- .action(async () => runSessionsServe(version));
294
- sessions
295
- .command("record")
296
- .description("Record the sessions one desktop scan found in a bound folder (used by the NuStack desktop)")
297
- .option("--scan <json>", "the scan payload as JSON, or @<path> to read it from a file")
298
- .option("--json", "emit the versioned machine envelope")
299
- .action(async (options) => runSessionsRecord(options, program.opts()));
300
- sessions
301
- .command("list")
302
- .description("List the sessions this machine's engine opened, and what each one's worktree and branch still hold")
303
- .option("--json", "emit the versioned machine envelope")
304
- .action(async (options) => runSessionsList(options));
305
- sessions
306
- .command("prune")
307
- .description("Reclaim the worktree and branch of a session that has ended (preview unless --yes)")
308
- .option("--session <id>", "reclaim one session instead of every reclaimable one")
309
- .option("--yes", "apply the preview without prompting")
310
- .option("--force", "also reclaim an unmerged or dirty session — never one whose engine is running")
311
- .option("--json", "emit the versioned machine envelope")
312
- .action(async (options) => runSessionsPrune(options));
313
- const harness = program.command("harness").description("Mount the Project's harness and compare it with the cloud pin");
314
- harness
315
- .command("mount [path]")
316
- .description("Mount the resolved harness version into a checkout (default: the current repository)")
317
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
318
- .option("--manifest <url>", "mount this manifest instead of the one the Project resolves")
319
- .option("--json", "emit the versioned machine envelope")
320
- .action(async (target, options) => runHarnessMount(target, options, program.opts()));
321
- harness
322
- .command("status")
323
- .description("Print the mounted harness against the cloud pin; exits 1 when they differ")
324
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
325
- .option("--json", "emit the versioned machine envelope")
326
- .action(async (options) => runHarnessStatus(options, program.opts()));
327
- const toolkit = program.command("toolkit").description("Inspect and reconcile the Project's toolkit pin");
328
- toolkit
329
- .command("status")
330
- .description("Compare the cloud pin against .nustack/workspace.json and nustack.service.json (F-026)")
331
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
332
- .option("--json", "emit the versioned machine envelope")
333
- .action(async (options) => runToolkitStatus(options, program.opts()));
334
- toolkit
335
- .command("reconcile")
336
- .description("Preview and apply the deterministic toolkit repair (no User content is touched)")
337
- .option("--project <id>", "the Project to act as (defaults to the bound repository)")
338
- .option("--yes", "apply the deterministic preview without prompting")
339
- .option("--json", "emit the versioned machine envelope")
340
- .action(async (options) => runToolkitReconcile(options, program.opts()));
341
- const agent = program.command("agent").description("The discovery hook an agent uses to find the running NuStack desktop");
342
- agent
343
- .command("context")
344
- .description("Print the SessionStart hook payload when the NuStack desktop is reachable (silent otherwise)")
345
- .action(async () => runAgentContext());
346
- const agentHook = agent.command("hook").description("Manage the `nustack agent context` SessionStart hook in ~/.claude/settings.json");
347
- agentHook
348
- .command("install")
349
- .description("Register the SessionStart hook (idempotent — a second install is a no-op)")
350
- .action(async () => runAgentHookInstall());
351
- agentHook
352
- .command("remove")
353
- .description("Remove exactly the managed SessionStart hook entry")
354
- .action(async () => runAgentHookRemove());
355
- function describeError(error) {
356
- const directCode = error?.code;
357
- if (directCode === "PROJECT_CONTEXT_MISSING") {
358
- return "no Project in context — run inside a bound repository (`.nustack/workspace.json`) or pass `--project <id>`.";
359
- }
360
- if (directCode === "ORGANIZATION_CONTEXT_MISSING") {
361
- return "no Organization in context — run `nustack organization use <id>` or pass `--organization <id>`.";
362
- }
363
- if (directCode === "TOOLKIT_INCOMPATIBLE") {
364
- return "the installed toolkit is incompatible with the Project's cloud pin — run `nustack toolkit reconcile`.";
365
- }
366
- const cause = error?.cause;
367
- const code = cause?.code;
368
- if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
369
- return "couldn't resolve the NuStack host — check your connection or pass --nustack-url.";
370
- }
371
- if (code === "ECONNREFUSED") {
372
- return "the NuStack host refused the connection — is it up? Override with --nustack-url.";
373
- }
374
- if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
375
- return "the request to NuStack timed out — check your connection or try again.";
376
- }
377
- if (error instanceof Error && error.message === "fetch failed") {
378
- return "couldn't reach NuStack — check your connection or pass --nustack-url.";
379
- }
380
- return error instanceof Error ? error.message : String(error);
381
- }
382
- function searchSeparatorInvocation(rawArgv) {
383
- const args = rawArgv.slice(2);
384
- const searchIdx = args.indexOf("search");
385
- if (searchIdx === -1)
386
- return null;
387
- if (searchIdx > 0 && args[searchIdx - 1] === "--nustack-url")
388
- return null;
389
- let cut = searchIdx + 1;
390
- while (cut < args.length) {
391
- const token = args[cut] ?? "";
392
- if (token === "--category" || token === "--limit" || token === "--nustack-url") {
393
- cut += 2;
394
- }
395
- else if (token.startsWith("--") && token !== "--") {
396
- cut += 1;
397
- }
398
- else {
399
- break;
400
- }
401
- }
402
- if (args[cut] !== "--")
403
- return null;
404
- const beforeSeparator = args.slice(0, cut);
405
- const literalKeywords = args.slice(cut + 1);
406
- return {
407
- run: async () => {
408
- const scoped = new Command();
409
- scoped.exitOverride();
410
- scoped.name("nustack").option("--nustack-url <url>", "");
411
- scoped
412
- .command("search [keywords...]")
413
- .option("--json", "")
414
- .option("--category <cat>", "")
415
- .option("--limit <n>", "", toLimit)
416
- .action(async (keywords, options) => runSearch(keywords, options, scoped.opts()));
417
- await scoped.parseAsync(["node", "nustack", ...beforeSeparator, ...literalKeywords]);
418
- },
419
- };
420
- }
421
- function isJsonInvocation(argv) {
422
- return argv.slice(2).includes("--json");
423
- }
424
- function commandLabelFromArgv(argv) {
425
- const args = argv.slice(2);
426
- const parts = [];
427
- for (let i = 0; i < args.length; i++) {
428
- const token = args[i] ?? "";
429
- if (token === "--nustack-url") {
430
- i++;
431
- continue;
432
- }
433
- if (token.startsWith("-"))
434
- break;
435
- parts.push(token);
436
- }
437
- return parts.length ? parts.join(" ") : "nustack";
438
- }
439
- function errorCodeOf(error) {
440
- const direct = error?.code ?? error?.cause?.code;
441
- return typeof direct === "string" ? direct : "UNEXPECTED";
442
- }
443
- try {
444
- const separated = searchSeparatorInvocation(process.argv);
445
- if (separated)
446
- await separated.run();
447
- else
448
- await program.parseAsync(process.argv);
449
- }
450
- catch (error) {
451
- if (isJsonInvocation(process.argv)) {
452
- printJsonError(commandLabelFromArgv(process.argv), { code: errorCodeOf(error), message: describeError(error) });
453
- }
454
- else {
455
- console.error(`nustack: ${describeError(error)}`);
456
- process.exitCode = 1;
457
- }
2
+ import { HOOK_SUBCOMMANDS } from "./lib/gate/subcommands.js";
3
+ const [, , command, subcommand] = process.argv;
4
+ if (command === "gate" && subcommand !== undefined && HOOK_SUBCOMMANDS.includes(subcommand)) {
5
+ const { runGateHook } = await import("./lib/gate/hook.js");
6
+ await runGateHook(subcommand);
7
+ }
8
+ else {
9
+ await import("./program.js");
458
10
  }