@indigoai-us/hq-cli 5.345.215-beta.0 → 5.345.217
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 +206 -1
- package/README.md +45 -0
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
- package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
- package/dist/command-catalog.generated.d.ts +105 -10
- package/dist/command-catalog.generated.js +127 -10
- package/dist/command-help.js +3 -1
- package/dist/command-registration-plan.d.ts +6 -0
- package/dist/command-registration-plan.js +1 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/auth.js +11 -52
- package/dist/commands/bot.js +75 -10
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud-demote.d.ts +19 -4
- package/dist/commands/cloud-demote.js +85 -12
- package/dist/commands/cloud-provision.d.ts +5 -1
- package/dist/commands/cloud-provision.js +6 -2
- package/dist/commands/cloud.d.ts +36 -0
- package/dist/commands/cloud.js +110 -27
- package/dist/commands/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/core.js +1 -0
- package/dist/commands/daemon.js +9 -1
- package/dist/commands/dm.js +7 -0
- package/dist/commands/doctor-usage.d.ts +8 -0
- package/dist/commands/doctor-usage.js +20 -0
- package/dist/commands/doctor.js +7 -1
- package/dist/commands/env.d.ts +18 -0
- package/dist/commands/env.js +82 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/install-global.js +2 -2
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +102 -26
- package/dist/commands/logout.d.ts +7 -0
- package/dist/commands/logout.js +41 -34
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- package/dist/commands/sources.d.ts +8 -2
- package/dist/commands/sources.js +65 -9
- package/dist/commands/sync-held.js +5 -2
- package/dist/commands/whoami.js +26 -1
- package/dist/data/command-states.json +15 -0
- package/dist/index.js +52 -4
- package/dist/lazy-commands.js +5 -6
- package/dist/lib/anywhere-person-setting.d.ts +2 -0
- package/dist/lib/anywhere-person-setting.js +6 -3
- package/dist/lib/billing/usage-card.d.ts +25 -4
- package/dist/lib/billing/usage-card.js +76 -9
- package/dist/lib/billing/usage-cost.d.ts +3 -3
- package/dist/lib/billing/usage-cost.js +35 -13
- package/dist/lib/billing/usage-only.js +4 -2
- package/dist/lib/billing/usage-rate-card.d.ts +2 -2
- package/dist/lib/billing/usage-rate-card.js +3 -0
- package/dist/lib/bot/fleet-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +126 -7
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- package/dist/lib/bot/inflight.d.ts +9 -0
- package/dist/lib/bot/inflight.js +10 -0
- package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
- package/dist/lib/bot/probe.js +7 -1
- package/dist/lib/bot/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
- package/dist/lib/bot/runtime/grok-acp.js +32 -14
- package/dist/lib/bot/runtime/grok.js +1 -1
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- package/dist/lib/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/flag-monitor.d.ts +8 -0
- package/dist/lib/daemon/flag-monitor.js +17 -6
- package/dist/lib/daemon/flag.d.ts +65 -1
- package/dist/lib/daemon/flag.js +190 -40
- package/dist/lib/daemon/ops/policy.js +62 -5
- package/dist/lib/daemon/paths.d.ts +72 -2
- package/dist/lib/daemon/paths.js +154 -3
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +79 -21
- package/dist/lib/daemon/selfcheck.d.ts +22 -0
- package/dist/lib/daemon/selfcheck.js +40 -1
- package/dist/lib/daemon/server.d.ts +5 -1
- package/dist/lib/daemon/server.js +17 -23
- package/dist/lib/daemon/state-file-switch.d.ts +57 -0
- package/dist/lib/daemon/state-file-switch.js +88 -0
- package/dist/lib/daemon/state-file.d.ts +198 -0
- package/dist/lib/daemon/state-file.js +419 -0
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
- package/dist/lib/daemon/timed-flag-monitors.js +75 -0
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +7 -1
- package/dist/lib/delivery/artifacts.js +29 -10
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -0
- package/dist/lib/delivery/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +21 -17
- package/dist/lib/delivery/enrollment.js +83 -5
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -0
- package/dist/lib/delivery/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +120 -4
- package/dist/lib/delivery/migrations.js +215 -15
- package/dist/lib/delivery/mqtt.d.ts +2 -0
- package/dist/lib/delivery/mqtt.js +7 -0
- package/dist/lib/delivery/reconciler.d.ts +65 -1
- package/dist/lib/delivery/reconciler.js +224 -13
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +2 -0
- package/dist/lib/delivery/store.js +4 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -0
- package/dist/lib/delivery/workers/macos.d.ts +16 -1
- package/dist/lib/delivery/workers/macos.js +54 -12
- package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +32 -22
- package/dist/lib/delivery/workers/windows.js +50 -64
- package/dist/lib/doctor/checks/host-core.d.ts +50 -0
- package/dist/lib/doctor/checks/host-core.js +269 -0
- package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
- package/dist/lib/doctor/checks/replay-recorder.js +261 -0
- package/dist/lib/doctor/registry.js +4 -0
- package/dist/lib/environment/profile.d.ts +239 -0
- package/dist/lib/environment/profile.js +251 -0
- package/dist/lib/hook-engine/reconcile.js +39 -13
- package/dist/lib/hook-engine/registration.d.ts +9 -0
- package/dist/lib/hook-engine/registration.js +19 -0
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
- package/dist/lib/hot-channels/adapters/slack.js +64 -21
- package/dist/lib/hot-channels/alert.d.ts +2 -0
- package/dist/lib/hot-channels/alert.js +8 -1
- package/dist/lib/hot-channels/contract.d.ts +12 -0
- package/dist/lib/hot-channels/contract.js +7 -0
- package/dist/lib/hot-channels/loop.js +1 -0
- package/dist/lib/hot-channels/run.d.ts +6 -0
- package/dist/lib/hot-channels/run.js +4 -0
- package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
- package/dist/lib/hot-channels/signals-pass.js +82 -41
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/install/claude-targets.d.ts +12 -1
- package/dist/lib/install/claude-targets.js +57 -5
- package/dist/lib/install/codex-targets.d.ts +2 -2
- package/dist/lib/install/codex-targets.js +36 -6
- package/dist/lib/install/hook-target.d.ts +3 -0
- package/dist/lib/install/hook-target.js +11 -0
- package/dist/lib/lanes/canonical-host.d.ts +35 -0
- package/dist/lib/lanes/canonical-host.js +65 -0
- package/dist/lib/lanes/host-capacity.d.ts +30 -0
- package/dist/lib/lanes/host-capacity.js +29 -3
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
- package/dist/lib/mesh/live/daemon/run.js +5 -2
- package/dist/lib/mesh/live/flush.d.ts +5 -1
- package/dist/lib/mesh/live/flush.js +12 -6
- package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
- package/dist/lib/mesh/live/reporting-privacy.js +56 -1
- package/dist/lib/mesh/live/spool.d.ts +7 -0
- package/dist/lib/mesh/live/spool.js +25 -0
- package/dist/lib/person-setting-cache.d.ts +38 -0
- package/dist/lib/person-setting-cache.js +98 -0
- package/dist/lib/safe-store.d.ts +245 -0
- package/dist/lib/safe-store.js +777 -0
- package/dist/lib/signals/engine.d.ts +29 -2
- package/dist/lib/signals/engine.js +103 -4
- package/dist/lib/signals/reply.js +73 -18
- package/dist/lib/signals/steps/adapters.js +7 -2
- package/dist/lib/signals/steps/extract.d.ts +13 -0
- package/dist/lib/signals/steps/extract.js +122 -6
- package/dist/main.js +46 -3
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
- package/dist/utils/auth-expiry.d.ts +8 -0
- package/dist/utils/auth-expiry.js +53 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- package/dist/utils/cli-telemetry.d.ts +21 -0
- package/dist/utils/cli-telemetry.js +34 -0
- package/dist/utils/command-usage.d.ts +275 -0
- package/dist/utils/command-usage.js +797 -0
- package/dist/utils/files-browse-acl.js +1 -1
- package/dist/utils/hook-trust.d.ts +7 -0
- package/dist/utils/hook-trust.js +31 -4
- package/dist/utils/host-registration.d.ts +126 -0
- package/dist/utils/host-registration.js +378 -0
- package/dist/utils/resident-package-preload.js +2 -0
- package/package.json +10 -8
- package/scripts/bench-core.mjs +1096 -0
- package/scripts/check-function-manifest.mjs +702 -0
- package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
- package/dist/lib/delivery/workers/windows-boundary.js +0 -693
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local command usage count, and the retiring-command gate, which ships
|
|
3
|
+
* switched off ({@link RETIRING_GATE_ENABLED}): no command is refused and no
|
|
4
|
+
* retiring notice is printed. The gate code is kept for when it is turned on.
|
|
5
|
+
*
|
|
6
|
+
* Every `hq` run appends one line to a file under `~/.hq/command-usage/`:
|
|
7
|
+
* the UTC date, a kind, a count, and the command path (`secrets env`,
|
|
8
|
+
* `doctor usage`). The command path is built only from command names the CLI
|
|
9
|
+
* itself declares, so an argument, a flag value, a company slug, a file path,
|
|
10
|
+
* the working directory, or an environment value can never be part of it.
|
|
11
|
+
*
|
|
12
|
+
* The file stays on this computer. Nothing here opens a socket, and the file
|
|
13
|
+
* sits outside every folder that sync, vault upload, telemetry, or `hq
|
|
14
|
+
* feedback` reads (see command-usage.test.ts for the checks). `HQ_TELEMETRY=0`
|
|
15
|
+
* therefore does not turn the count off.
|
|
16
|
+
*
|
|
17
|
+
* `src/index.ts` imports this module on every route, including the hook fast
|
|
18
|
+
* routes, so it imports Node builtins and the store helper only (which imports
|
|
19
|
+
* Node builtins only), and the per-run work is one small
|
|
20
|
+
* append: no read of the usage file, no directory listing. A write error is
|
|
21
|
+
* swallowed; counting must never fail or slow a command.
|
|
22
|
+
*
|
|
23
|
+
* Size: the file is compacted to one line per date, kind and command once it
|
|
24
|
+
* passes COMMAND_USAGE_COMPACT_AT_BYTES. Compaction drops dates older than the
|
|
25
|
+
* 30-day window, and then the oldest dates until the result fits
|
|
26
|
+
* COMMAND_USAGE_MAX_COMPACTED_BYTES. The file from before the last compaction
|
|
27
|
+
* is kept until the next one, so the folder holds about twice the compaction
|
|
28
|
+
* threshold at most (about 512 KiB).
|
|
29
|
+
*
|
|
30
|
+
* Every read and write of the usage folder goes through the shared store
|
|
31
|
+
* helper (`src/lib/safe-store.ts`): the folder is held open and checked by its
|
|
32
|
+
* descriptor, files are opened without following a link and without blocking,
|
|
33
|
+
* and only a regular single-link file of this user is written or read. A named
|
|
34
|
+
* pipe, a link (symbolic or hard), or a folder at the usage path means no count
|
|
35
|
+
* is kept; so does a usage folder that is a link, belongs to another user, or
|
|
36
|
+
* is writable by the group or others, and a folder swapped for another while
|
|
37
|
+
* a write runs. The command runs as it would otherwise.
|
|
38
|
+
*
|
|
39
|
+
* When the gate is switched on, it matches the whole command path. An entry
|
|
40
|
+
* for a command group (`core job`) does not gate the commands under it
|
|
41
|
+
* (`core job run`); each command to retire is listed by its own path. While it
|
|
42
|
+
* is off, the `refused` count stays 0 and `hq doctor usage` does not show it.
|
|
43
|
+
*/
|
|
44
|
+
import { randomBytes } from "node:crypto";
|
|
45
|
+
import * as fs from "node:fs";
|
|
46
|
+
import * as os from "node:os";
|
|
47
|
+
import * as path from "node:path";
|
|
48
|
+
import { openStoreDir } from "../lib/safe-store.js";
|
|
49
|
+
/**
|
|
50
|
+
* The switch for the retiring-command gate. Off: no command is refused and no
|
|
51
|
+
* retiring notice is printed, whatever `src/data/command-states.json` marks.
|
|
52
|
+
*
|
|
53
|
+
* Owner decision (Corey, 2026-11-13): "let's not retire commands right now.
|
|
54
|
+
* just evolve towards new platform". Every command runs as it did in
|
|
55
|
+
* v5.345.215. The marking data and the local usage count stay, so the gate can
|
|
56
|
+
* be switched back on later by setting this to true.
|
|
57
|
+
*/
|
|
58
|
+
export const RETIRING_GATE_ENABLED = false;
|
|
59
|
+
/**
|
|
60
|
+
* Global flag that, with the gate on, runs a command whose state is
|
|
61
|
+
* `retiring`. With the gate off it is still accepted and taken out of argv
|
|
62
|
+
* where hq reads it; it only marks the run of a marked command as a
|
|
63
|
+
* `still-use` run in the local count.
|
|
64
|
+
*/
|
|
65
|
+
export const STILL_USE_FLAG = "--i-still-use-this";
|
|
66
|
+
/** Help text for the flag on the root program (main.ts and command-help.ts). */
|
|
67
|
+
export const STILL_USE_FLAG_DESCRIPTION = RETIRING_GATE_ENABLED
|
|
68
|
+
? "Run a command that is being retired (these runs are counted apart from the rest)"
|
|
69
|
+
: "Accepted; only counts this run apart in `hq doctor usage`";
|
|
70
|
+
/** `hq doctor usage` reports this many days, and compaction keeps the same. */
|
|
71
|
+
export const COMMAND_USAGE_WINDOW_DAYS = 30;
|
|
72
|
+
/** The usage file is compacted once an append takes it past this size. */
|
|
73
|
+
export const COMMAND_USAGE_COMPACT_AT_BYTES = 256 * 1024;
|
|
74
|
+
/** A compacted file is cut to this size by dropping its oldest dates. */
|
|
75
|
+
export const COMMAND_USAGE_MAX_COMPACTED_BYTES = 128 * 1024;
|
|
76
|
+
/**
|
|
77
|
+
* Appends stop at this size. It is reached only when compaction keeps failing
|
|
78
|
+
* (for example a lock that cannot be taken); normal use stays near the
|
|
79
|
+
* compaction threshold.
|
|
80
|
+
*/
|
|
81
|
+
export const COMMAND_USAGE_HARD_MAX_BYTES = 1024 * 1024;
|
|
82
|
+
/** Folder under `~/.hq`. Not `logs/`, `locks/` or `jobs/`: `hq feedback` reads those. */
|
|
83
|
+
export const COMMAND_USAGE_DIRNAME = "command-usage";
|
|
84
|
+
export const COMMAND_USAGE_FILENAME = "usage.tsv";
|
|
85
|
+
const COMPACT_LOCK_FILENAME = "compact.lock";
|
|
86
|
+
const COMPACT_LOCK_STALE_MS = 60_000;
|
|
87
|
+
const ROTATED_FILE_PATTERN = /^usage\.([a-z0-9-]+)\.old$/;
|
|
88
|
+
const MERGED_MARKER = "#merged";
|
|
89
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
90
|
+
const MAX_COMMAND_PATH_LENGTH = 200;
|
|
91
|
+
/** Command names only: letters, digits and `:._-`, separated by single spaces. */
|
|
92
|
+
const COMMAND_PATH_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:._-]*(?: [A-Za-z0-9][A-Za-z0-9:._-]*)*$/;
|
|
93
|
+
const KIND_CODE = {
|
|
94
|
+
run: "r",
|
|
95
|
+
"still-use": "f",
|
|
96
|
+
refused: "x",
|
|
97
|
+
};
|
|
98
|
+
const CODE_KIND = {
|
|
99
|
+
r: "run",
|
|
100
|
+
f: "still-use",
|
|
101
|
+
x: "refused",
|
|
102
|
+
};
|
|
103
|
+
function isTestRun(env) {
|
|
104
|
+
return env.NODE_ENV === "test" || env.VITEST === "true";
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* True when this copy of the CLI runs from its source checkout: the package
|
|
108
|
+
* root holds `vitest.config.ts`, which the published package does not ship.
|
|
109
|
+
*/
|
|
110
|
+
function runsFromSourceCheckout() {
|
|
111
|
+
try {
|
|
112
|
+
const here = import.meta.dirname;
|
|
113
|
+
return fs.existsSync(typeof here === "string"
|
|
114
|
+
? path.join(here, "..", "..", "vitest.config.ts")
|
|
115
|
+
: new URL("../../vitest.config.ts", import.meta.url));
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Where the count is kept, or null when this run keeps none.
|
|
123
|
+
*
|
|
124
|
+
* A test run never writes to the real home: it counts only into the folder a
|
|
125
|
+
* test names with HQ_TEST_COMMAND_USAGE_DIR. That variable is ignored outside
|
|
126
|
+
* a test run, so it is not a way to move or switch off the count.
|
|
127
|
+
*
|
|
128
|
+
* A test run is `NODE_ENV=test` or `VITEST=true`. A person who has
|
|
129
|
+
* `NODE_ENV=test` set in their shell therefore keeps no count (the README says
|
|
130
|
+
* so). The retiring gate does not depend on it: see {@link loadCommandStates}.
|
|
131
|
+
*/
|
|
132
|
+
export function commandUsageDir(env = process.env) {
|
|
133
|
+
if (isTestRun(env))
|
|
134
|
+
return env.HQ_TEST_COMMAND_USAGE_DIR?.trim() || null;
|
|
135
|
+
const home = env.HOME?.trim() || os.homedir();
|
|
136
|
+
return path.join(home, ".hq", COMMAND_USAGE_DIRNAME);
|
|
137
|
+
}
|
|
138
|
+
let cachedStates;
|
|
139
|
+
let admittedThisProcess = false;
|
|
140
|
+
/** Test seam: forget the cached state table and the once-per-process mark. */
|
|
141
|
+
export function _resetCommandUsageForTests() {
|
|
142
|
+
cachedStates = undefined;
|
|
143
|
+
admittedThisProcess = false;
|
|
144
|
+
}
|
|
145
|
+
/** `data/command-states.json` beside this module's folder (src/ and dist/ alike). */
|
|
146
|
+
function shippedCommandStatesPath() {
|
|
147
|
+
// `import.meta.dirname` (Node 20.11 and later) avoids building a URL object
|
|
148
|
+
// on every run; older Node 20 releases take the URL form.
|
|
149
|
+
const here = import.meta.dirname;
|
|
150
|
+
return typeof here === "string"
|
|
151
|
+
? path.join(here, "..", "data", "command-states.json")
|
|
152
|
+
: new URL("../data/command-states.json", import.meta.url);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Read the command states that ship inside the CLI. The file lists only
|
|
156
|
+
* commands whose state is not `live`; a command absent from it is `live`.
|
|
157
|
+
* A missing or damaged file gates nothing: a broken table must not stop
|
|
158
|
+
* every command from running.
|
|
159
|
+
*
|
|
160
|
+
* HQ_TEST_COMMAND_STATES_FILE names another table for this repository's own
|
|
161
|
+
* tests. It is read only in a test run of a source checkout. An installed CLI
|
|
162
|
+
* never reads it, whatever the environment holds, so a person's environment
|
|
163
|
+
* cannot switch the gate off or point it at another table.
|
|
164
|
+
*/
|
|
165
|
+
export function loadCommandStates(env = process.env, sourceCheckout = runsFromSourceCheckout) {
|
|
166
|
+
if (cachedStates)
|
|
167
|
+
return cachedStates;
|
|
168
|
+
let commands = {};
|
|
169
|
+
try {
|
|
170
|
+
const named = isTestRun(env) ? env.HQ_TEST_COMMAND_STATES_FILE?.trim() : undefined;
|
|
171
|
+
const override = named && sourceCheckout() ? named : undefined;
|
|
172
|
+
const source = override || shippedCommandStatesPath();
|
|
173
|
+
const document = JSON.parse(fs.readFileSync(source, "utf8"));
|
|
174
|
+
if (document !== null && typeof document === "object") {
|
|
175
|
+
const { schema, commands: listed } = document;
|
|
176
|
+
if (schema === 1 && listed !== null && typeof listed === "object" && !Array.isArray(listed)) {
|
|
177
|
+
commands = listed;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// Treated as an empty table.
|
|
183
|
+
}
|
|
184
|
+
cachedStates = commands;
|
|
185
|
+
return commands;
|
|
186
|
+
}
|
|
187
|
+
function stateOf(states, commandPath) {
|
|
188
|
+
if (!commandPath || !Object.prototype.hasOwnProperty.call(states, commandPath))
|
|
189
|
+
return undefined;
|
|
190
|
+
const entry = states[commandPath];
|
|
191
|
+
return entry !== null && typeof entry === "object" && typeof entry.state === "string" ? entry : undefined;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* True when the flag appears anywhere before a `--` terminator. `src/index.ts`
|
|
195
|
+
* uses this to send such a run to the full command graph, which knows the
|
|
196
|
+
* command names and decides whether the flag is hq's ({@link takeStillUseFlag}).
|
|
197
|
+
*/
|
|
198
|
+
export function hasStillUseFlag(argv) {
|
|
199
|
+
const index = argv.indexOf(STILL_USE_FLAG, 2);
|
|
200
|
+
if (index === -1)
|
|
201
|
+
return false;
|
|
202
|
+
const terminator = argv.indexOf("--", 2);
|
|
203
|
+
return terminator === -1 || index < terminator;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Take the flag out of `argv` in place where hq reads it, and say whether it
|
|
207
|
+
* was there.
|
|
208
|
+
*
|
|
209
|
+
* hq reads the flag only before the command's own arguments begin: before the
|
|
210
|
+
* command name, between the names of a command path, or directly after the
|
|
211
|
+
* last name (`hq --i-still-use-this whoami`, `hq core --i-still-use-this job
|
|
212
|
+
* run`, `hq whoami --i-still-use-this`). The first operand or option of the
|
|
213
|
+
* command ends that span, and so does `--`. A flag after that point stays in
|
|
214
|
+
* `argv` and belongs to the command: `hq run tool --i-still-use-this` hands it
|
|
215
|
+
* to `tool`.
|
|
216
|
+
*
|
|
217
|
+
* `root` is the command graph, so a name is told from an operand by the
|
|
218
|
+
* commands the CLI declares. This runs before Commander parses `argv`, which
|
|
219
|
+
* therefore never sees a flag hq took, and neither does a command that reads
|
|
220
|
+
* its arguments straight from `process.argv`.
|
|
221
|
+
*/
|
|
222
|
+
export function takeStillUseFlag(argv, root) {
|
|
223
|
+
let node = root;
|
|
224
|
+
let found = false;
|
|
225
|
+
let index = 2;
|
|
226
|
+
while (index < argv.length) {
|
|
227
|
+
const token = argv[index];
|
|
228
|
+
if (token === STILL_USE_FLAG) {
|
|
229
|
+
argv.splice(index, 1);
|
|
230
|
+
found = true;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (token === "--verbose") {
|
|
234
|
+
// The root's other flag. It takes no value.
|
|
235
|
+
index += 1;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
if (token.startsWith("-"))
|
|
239
|
+
break;
|
|
240
|
+
const child = node.commands.find((command) => command.name() === token || command.aliases().includes(token));
|
|
241
|
+
if (!child)
|
|
242
|
+
break;
|
|
243
|
+
node = child;
|
|
244
|
+
index += 1;
|
|
245
|
+
}
|
|
246
|
+
return found;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The command path of the command Commander is about to run.
|
|
250
|
+
*
|
|
251
|
+
* `canonical` joins the declared command names from the root down. `typed`
|
|
252
|
+
* is the same path with each name replaced by the alias the person typed,
|
|
253
|
+
* when they typed one.
|
|
254
|
+
*
|
|
255
|
+
* Nothing is read from argv. Commander dispatches a subcommand on the first
|
|
256
|
+
* operand its parent was left with (`parent.args[0]`), after the parent's
|
|
257
|
+
* own options and their values are taken out. That word is used only when it
|
|
258
|
+
* is a declared name or alias of the dispatched command, so a positional
|
|
259
|
+
* value or an option value cannot become part of the path.
|
|
260
|
+
*/
|
|
261
|
+
export function commandPathOf(actionCommand) {
|
|
262
|
+
const chain = [];
|
|
263
|
+
for (let node = actionCommand; node && node.parent; node = node.parent) {
|
|
264
|
+
chain.unshift(node);
|
|
265
|
+
}
|
|
266
|
+
const typed = chain.map((node) => {
|
|
267
|
+
const dispatched = node.parent?.args[0];
|
|
268
|
+
return dispatched !== undefined && node.aliases().includes(dispatched) ? dispatched : node.name();
|
|
269
|
+
});
|
|
270
|
+
return { typed: typed.join(" "), canonical: chain.map((node) => node.name()).join(" ") };
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* `YYYY-MM-DD` in UTC, by integer arithmetic. The first `Date` formatting call
|
|
274
|
+
* in a process costs about a millisecond, which is too much for a hook run.
|
|
275
|
+
* (Days-to-civil conversion for the proleptic Gregorian calendar.)
|
|
276
|
+
*/
|
|
277
|
+
function utcDate(epochMs) {
|
|
278
|
+
const shifted = Math.floor(epochMs / DAY_MS) + 719_468;
|
|
279
|
+
const era = Math.floor(shifted / 146_097);
|
|
280
|
+
const dayOfEra = shifted - era * 146_097;
|
|
281
|
+
const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1_460) + Math.floor(dayOfEra / 36_524) - Math.floor(dayOfEra / 146_096)) / 365);
|
|
282
|
+
const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
|
|
283
|
+
const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
|
|
284
|
+
const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
|
|
285
|
+
const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9;
|
|
286
|
+
const year = yearOfEra + era * 400 + (month <= 2 ? 1 : 0);
|
|
287
|
+
return `${String(year).padStart(4, "0")}-${month < 10 ? "0" : ""}${month}-${day < 10 ? "0" : ""}${day}`;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Append one use of `commandPath`. Never throws. Creates the usage folder but
|
|
291
|
+
* never `~/.hq` itself: a computer with no HQ state keeps no count.
|
|
292
|
+
*/
|
|
293
|
+
export function recordCommandUse(commandPath, kind, options = {}) {
|
|
294
|
+
try {
|
|
295
|
+
const dir = options.dir === undefined ? commandUsageDir(options.env) : options.dir;
|
|
296
|
+
if (!dir)
|
|
297
|
+
return;
|
|
298
|
+
if (commandPath.length > MAX_COMMAND_PATH_LENGTH || !COMMAND_PATH_PATTERN.test(commandPath))
|
|
299
|
+
return;
|
|
300
|
+
const now = options.now ?? Date.now();
|
|
301
|
+
const line = `${utcDate(now)}\t${KIND_CODE[kind]}\t1\t${commandPath}\n`;
|
|
302
|
+
withUsageStore(dir, true, undefined, (store) => {
|
|
303
|
+
let size = appendUsageLine(store, line);
|
|
304
|
+
// -1: the file this process had open was removed before the line landed
|
|
305
|
+
// (two compactions ran in between). Write it again, once, to the live file.
|
|
306
|
+
if (size === -1)
|
|
307
|
+
size = appendUsageLine(store, line);
|
|
308
|
+
if (size > COMMAND_USAGE_COMPACT_AT_BYTES)
|
|
309
|
+
compactWithLock(store, now);
|
|
310
|
+
}, options.at);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
// Counting is best effort.
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Hold the usage folder open through the shared store helper, or return null
|
|
318
|
+
* when no count can be kept there.
|
|
319
|
+
*
|
|
320
|
+
* The helper refuses a folder that is a link, belongs to another user, or is
|
|
321
|
+
* writable by group or others, and checks the folders above it. With
|
|
322
|
+
* `create`, a missing leaf folder is made (mode 0700), but only when its
|
|
323
|
+
* parent (`~/.hq`) already exists: a computer with no HQ state keeps no count.
|
|
324
|
+
*/
|
|
325
|
+
function openUsageStore(dir, create, at) {
|
|
326
|
+
if (create) {
|
|
327
|
+
try {
|
|
328
|
+
if (!fs.lstatSync(path.dirname(dir)).isDirectory())
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const opened = openStoreDir(dir, { create, at });
|
|
336
|
+
return opened.ok ? opened.value : null;
|
|
337
|
+
}
|
|
338
|
+
/** Run `work` with the usage folder held, or return `fallback` when it cannot be held. */
|
|
339
|
+
function withUsageStore(dir, create, fallback, work, at) {
|
|
340
|
+
const store = openUsageStore(dir, create, at);
|
|
341
|
+
if (store === null)
|
|
342
|
+
return fallback;
|
|
343
|
+
try {
|
|
344
|
+
return work(store);
|
|
345
|
+
}
|
|
346
|
+
finally {
|
|
347
|
+
store.close();
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Whether `dir` is a usage folder this module works in (see
|
|
352
|
+
* {@link openUsageStore}). With `create`, a missing leaf folder is made first.
|
|
353
|
+
*/
|
|
354
|
+
export function usageDirIsSafe(dir, create = false) {
|
|
355
|
+
return withUsageStore(dir, create, false, () => true);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Append `line` to the usage file of the held folder. Returns the file size
|
|
359
|
+
* after, -1 when the file had no name left after the write (see the caller),
|
|
360
|
+
* or 0 when no count was kept.
|
|
361
|
+
*
|
|
362
|
+
* The helper opens the file without following a link and without blocking,
|
|
363
|
+
* creates it only with O_EXCL, keeps only a regular single-link file of this
|
|
364
|
+
* user, and writes only while the folder's path still leads to the held
|
|
365
|
+
* folder. A file already at the size cap is not appended to; its size is
|
|
366
|
+
* returned so the caller compacts it.
|
|
367
|
+
*
|
|
368
|
+
* A concurrent compaction can make the helper refuse a write that is safe to
|
|
369
|
+
* try again: the file was renamed between its open and the check after it
|
|
370
|
+
* (`file-changed`), it was gone (`missing`), or another hq process created
|
|
371
|
+
* the new file first (`EEXIST` on the exclusive create). Those are tried
|
|
372
|
+
* again, up to {@link APPEND_ATTEMPTS} times in all; each try repeats the
|
|
373
|
+
* folder check. A swapped folder (`folder-changed`) and every other refusal
|
|
374
|
+
* are never tried again.
|
|
375
|
+
*/
|
|
376
|
+
function appendUsageLine(store, line) {
|
|
377
|
+
for (let attempt = 1;; attempt += 1) {
|
|
378
|
+
const appended = store.appendLine(COMMAND_USAGE_FILENAME, line, { maxBytes: COMMAND_USAGE_HARD_MAX_BYTES });
|
|
379
|
+
if (appended.ok)
|
|
380
|
+
return appended.value.unlinked ? -1 : appended.value.size;
|
|
381
|
+
if (appended.code === "too-large")
|
|
382
|
+
return COMMAND_USAGE_HARD_MAX_BYTES;
|
|
383
|
+
if (attempt >= APPEND_ATTEMPTS || !appendRaceRefusal(appended))
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
/** Tries of one append in all, when a concurrent compaction got in the way. */
|
|
388
|
+
const APPEND_ATTEMPTS = 3;
|
|
389
|
+
/** Whether an append refusal comes from a concurrent rotation or create, and may be tried again. */
|
|
390
|
+
function appendRaceRefusal(refused) {
|
|
391
|
+
if (refused.code === "file-changed" || refused.code === "missing")
|
|
392
|
+
return true;
|
|
393
|
+
return refused.code === "io-error" && refused.errno === "EEXIST";
|
|
394
|
+
}
|
|
395
|
+
/** The one message a refused command prints. */
|
|
396
|
+
export function retiringRefusalMessage(commandPath, entry) {
|
|
397
|
+
const replacement = typeof entry.replacedBy === "string" ? entry.replacedBy.trim() : "";
|
|
398
|
+
const instead = replacement ? `Use instead: ${replacement}.` : "No replacement is listed.";
|
|
399
|
+
return (`"${commandPath}" is being retired and did not run. ${instead} ` +
|
|
400
|
+
`To run it anyway, add ${STILL_USE_FLAG} directly after the command name: hq ${commandPath} ${STILL_USE_FLAG}`);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Count one command run and apply the retiring gate.
|
|
404
|
+
*
|
|
405
|
+
* The gate is off ({@link RETIRING_GATE_ENABLED}): this then always returns
|
|
406
|
+
* null and only counts the run. A run of a command marked `retiring` that
|
|
407
|
+
* carries the flag is still counted as `still-use`; nothing is counted as
|
|
408
|
+
* `refused`.
|
|
409
|
+
*
|
|
410
|
+
* With the gate on, returns null when the command may run, or the refusal
|
|
411
|
+
* message when its state is `retiring` and the run does not carry the flag. A refused attempt
|
|
412
|
+
* is counted as `refused`, and a run that used the flag on a retiring command
|
|
413
|
+
* as `still-use`, both apart from ordinary runs. Other states are not gated.
|
|
414
|
+
*
|
|
415
|
+
* The table is matched on the whole command path, as typed and by declared
|
|
416
|
+
* names. An entry for a group does not gate the commands under it, and an
|
|
417
|
+
* entry for a command does not gate the group above it. Retiring a group
|
|
418
|
+
* means listing each of its commands, so a command is never refused without
|
|
419
|
+
* its own entry.
|
|
420
|
+
*
|
|
421
|
+
* One process counts one run: a fast route that hands the command on to the
|
|
422
|
+
* full command graph is not counted a second time there.
|
|
423
|
+
*/
|
|
424
|
+
export function admitCommandRun(run, options = {}) {
|
|
425
|
+
if (admittedThisProcess)
|
|
426
|
+
return null;
|
|
427
|
+
admittedThisProcess = true;
|
|
428
|
+
const gateEnabled = options.gateEnabled ?? RETIRING_GATE_ENABLED;
|
|
429
|
+
let entry;
|
|
430
|
+
try {
|
|
431
|
+
const states = options.states ?? loadCommandStates(options.env);
|
|
432
|
+
entry = stateOf(states, run.typed) ?? stateOf(states, run.canonical);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
entry = undefined;
|
|
436
|
+
}
|
|
437
|
+
const retiring = entry?.state === "retiring";
|
|
438
|
+
if (gateEnabled && entry && retiring && !run.stillUse) {
|
|
439
|
+
recordCommandUse(run.typed, "refused", options);
|
|
440
|
+
return retiringRefusalMessage(run.typed, entry);
|
|
441
|
+
}
|
|
442
|
+
recordCommandUse(run.typed, retiring && run.stillUse ? "still-use" : "run", options);
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
/** The largest usage file that is read: the append cap plus one line. */
|
|
446
|
+
const USAGE_READ_MAX_BYTES = COMMAND_USAGE_HARD_MAX_BYTES + 4096;
|
|
447
|
+
/**
|
|
448
|
+
* The usage files of the held folder. A name that is not a regular
|
|
449
|
+
* single-link file of this user (a link, a pipe, a folder) is skipped, and
|
|
450
|
+
* so is one removed by a concurrent compaction.
|
|
451
|
+
*/
|
|
452
|
+
function readSources(store, includeLive) {
|
|
453
|
+
const listed = store.list();
|
|
454
|
+
if (!listed.ok)
|
|
455
|
+
return [];
|
|
456
|
+
const sources = [];
|
|
457
|
+
for (const name of listed.value) {
|
|
458
|
+
const rotated = ROTATED_FILE_PATTERN.exec(name);
|
|
459
|
+
if (!rotated && !(includeLive && name === COMMAND_USAGE_FILENAME))
|
|
460
|
+
continue;
|
|
461
|
+
const read = store.read(name, { maxBytes: USAGE_READ_MAX_BYTES });
|
|
462
|
+
if (read.ok)
|
|
463
|
+
sources.push({ id: rotated ? rotated[1] : null, name, bytes: read.value });
|
|
464
|
+
}
|
|
465
|
+
return sources;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* How many leading bytes of each rotated file a compaction has already folded
|
|
469
|
+
* into the live file, read from the `#merged <id> <bytes>` markers.
|
|
470
|
+
*/
|
|
471
|
+
function mergedOffsets(sources) {
|
|
472
|
+
const offsets = new Map();
|
|
473
|
+
for (const source of sources) {
|
|
474
|
+
for (const line of source.bytes.toString("utf8").split("\n")) {
|
|
475
|
+
if (!line.startsWith(`${MERGED_MARKER}\t`))
|
|
476
|
+
continue;
|
|
477
|
+
const [, id, bytesText] = line.split("\t");
|
|
478
|
+
if (!id || !bytesText || !/^\d{1,12}$/.test(bytesText))
|
|
479
|
+
continue;
|
|
480
|
+
offsets.set(id, Math.max(offsets.get(id) ?? 0, Number(bytesText)));
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return offsets;
|
|
484
|
+
}
|
|
485
|
+
/** Add every usage line of `text` to `totals`, keyed `date\tcode\tcommand`. */
|
|
486
|
+
function addUsageLines(totals, text) {
|
|
487
|
+
for (const line of text.split("\n")) {
|
|
488
|
+
if (!line || line.startsWith("#"))
|
|
489
|
+
continue;
|
|
490
|
+
const [date, code, countText, commandPath, extra] = line.split("\t");
|
|
491
|
+
if (extra !== undefined || !date || !code || !countText || !commandPath)
|
|
492
|
+
continue;
|
|
493
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !(code in CODE_KIND))
|
|
494
|
+
continue;
|
|
495
|
+
if (!/^\d{1,9}$/.test(countText) || !COMMAND_PATH_PATTERN.test(commandPath))
|
|
496
|
+
continue;
|
|
497
|
+
const key = `${date}\t${code}\t${commandPath}`;
|
|
498
|
+
totals.set(key, (totals.get(key) ?? 0) + Number(countText));
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Totals over the live file and the part of each rotated file not folded yet. */
|
|
502
|
+
function collectTotals(sources, offsets) {
|
|
503
|
+
const totals = new Map();
|
|
504
|
+
for (const source of sources) {
|
|
505
|
+
const offset = source.id === null ? 0 : Math.min(offsets.get(source.id) ?? 0, source.bytes.length);
|
|
506
|
+
addUsageLines(totals, source.bytes.subarray(offset).toString("utf8"));
|
|
507
|
+
}
|
|
508
|
+
return totals;
|
|
509
|
+
}
|
|
510
|
+
function windowStart(now) {
|
|
511
|
+
return utcDate(now - (COMMAND_USAGE_WINDOW_DAYS - 1) * DAY_MS);
|
|
512
|
+
}
|
|
513
|
+
/** One line per date, kind and command, oldest first, within the window and the size cap. */
|
|
514
|
+
function renderCompacted(totals, now) {
|
|
515
|
+
const first = windowStart(now);
|
|
516
|
+
const lines = [];
|
|
517
|
+
for (const [key, count] of [...totals.entries()].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
518
|
+
const [date, code, commandPath] = key.split("\t");
|
|
519
|
+
if (date < first)
|
|
520
|
+
continue;
|
|
521
|
+
lines.push(`${date}\t${code}\t${count}\t${commandPath}\n`);
|
|
522
|
+
}
|
|
523
|
+
let bytes = lines.reduce((sum, line) => sum + Buffer.byteLength(line), 0);
|
|
524
|
+
let start = 0;
|
|
525
|
+
while (bytes > COMMAND_USAGE_MAX_COMPACTED_BYTES && start < lines.length) {
|
|
526
|
+
// Drop the whole oldest date, so no date is left half counted.
|
|
527
|
+
const oldest = lines[start].slice(0, 10);
|
|
528
|
+
while (start < lines.length && lines[start].startsWith(oldest)) {
|
|
529
|
+
bytes -= Buffer.byteLength(lines[start]);
|
|
530
|
+
start += 1;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return lines.slice(start).join("");
|
|
534
|
+
}
|
|
535
|
+
/** A random part for a name in the usage folder, so no name can be planted ahead. */
|
|
536
|
+
function randomPart() {
|
|
537
|
+
return randomBytes(8).toString("hex");
|
|
538
|
+
}
|
|
539
|
+
/** A lock token: when it was taken (epoch milliseconds, base 36), then the process and a random part. */
|
|
540
|
+
function newLockToken(now) {
|
|
541
|
+
return `${Math.floor(now).toString(36)}.${process.pid.toString(36)}.${randomPart()}`;
|
|
542
|
+
}
|
|
543
|
+
/** The lock file holds one token; anything larger is not a lock this module wrote. */
|
|
544
|
+
const LOCK_READ_MAX_BYTES = 256;
|
|
545
|
+
/** A stale lock moved aside during a takeover, removed by the process that moved it. */
|
|
546
|
+
const ASIDE_LOCK_PATTERN = /^compact\.lock\.[0-9a-f]+\.stale$/;
|
|
547
|
+
/** The token in the lock file, or null when there is no readable lock file. */
|
|
548
|
+
function lockHolder(store) {
|
|
549
|
+
const read = store.read(COMPACT_LOCK_FILENAME, { maxBytes: LOCK_READ_MAX_BYTES });
|
|
550
|
+
return read.ok ? read.value.toString("utf8") : null;
|
|
551
|
+
}
|
|
552
|
+
/** Whether this process still holds the lock it took as `token`. */
|
|
553
|
+
function holdsCompactLock(store, token) {
|
|
554
|
+
return lockHolder(store) === token;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Take over a lock judged stale, whose file held `judged`. Returns the new
|
|
558
|
+
* token, or null when another process took it over first.
|
|
559
|
+
*
|
|
560
|
+
* The stale lock file is renamed aside under a random name. A rename succeeds
|
|
561
|
+
* for one process only; every other process that judged the same lock stale
|
|
562
|
+
* finds the name gone, or moves the lock the winner has just made. The moved
|
|
563
|
+
* file is therefore checked: when it is not the file judged stale (another
|
|
564
|
+
* token, or a fresh time), it is put back and this process stands down. The
|
|
565
|
+
* winner then makes its own lock with O_EXCL, which a process that arrives
|
|
566
|
+
* fresh in between can win instead.
|
|
567
|
+
*/
|
|
568
|
+
function claimStaleLock(store, judged, now) {
|
|
569
|
+
const aside = `${COMPACT_LOCK_FILENAME}.${randomPart()}.stale`;
|
|
570
|
+
if (!store.rename(COMPACT_LOCK_FILENAME, aside).ok)
|
|
571
|
+
return null;
|
|
572
|
+
const moved = store.read(aside, { maxBytes: LOCK_READ_MAX_BYTES });
|
|
573
|
+
const facts = store.stat(aside);
|
|
574
|
+
// Left for a later sweep when it cannot be read.
|
|
575
|
+
if (!moved.ok || !facts.ok)
|
|
576
|
+
return null;
|
|
577
|
+
store.remove(aside);
|
|
578
|
+
if (moved.value.toString("utf8") !== judged || now - facts.value.mtimeMs <= COMPACT_LOCK_STALE_MS) {
|
|
579
|
+
store.createExclusive(COMPACT_LOCK_FILENAME, moved.value);
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
const token = newLockToken(now);
|
|
583
|
+
const created = store.createExclusive(COMPACT_LOCK_FILENAME, token);
|
|
584
|
+
return created.ok && created.value ? token : null;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Take the compaction lock in the held folder. Returns this process's token,
|
|
588
|
+
* or null when another process holds it or the lock name is not a regular
|
|
589
|
+
* file of this user.
|
|
590
|
+
*
|
|
591
|
+
* The lock is a file made with O_CREAT|O_EXCL|O_NOFOLLOW that holds the
|
|
592
|
+
* holder's token. A lock file older than a minute (by its modification time)
|
|
593
|
+
* is taken over by {@link claimStaleLock}.
|
|
594
|
+
*/
|
|
595
|
+
function acquireHeldLock(store, now) {
|
|
596
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
597
|
+
const token = newLockToken(now);
|
|
598
|
+
const created = store.createExclusive(COMPACT_LOCK_FILENAME, token);
|
|
599
|
+
if (!created.ok)
|
|
600
|
+
return null;
|
|
601
|
+
if (created.value)
|
|
602
|
+
return token;
|
|
603
|
+
const facts = store.stat(COMPACT_LOCK_FILENAME);
|
|
604
|
+
if (!facts.ok) {
|
|
605
|
+
// Released a moment ago: try again. A link or folder at the name: no lock.
|
|
606
|
+
if (facts.code === "missing")
|
|
607
|
+
continue;
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
610
|
+
if (now - facts.value.mtimeMs <= COMPACT_LOCK_STALE_MS)
|
|
611
|
+
return null;
|
|
612
|
+
const judged = lockHolder(store);
|
|
613
|
+
if (judged === null)
|
|
614
|
+
continue;
|
|
615
|
+
return claimStaleLock(store, judged, now);
|
|
616
|
+
}
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
/** Give the lock back. Does nothing when another process has taken it over. */
|
|
620
|
+
function releaseHeldLock(store, token) {
|
|
621
|
+
if (holdsCompactLock(store, token))
|
|
622
|
+
store.remove(COMPACT_LOCK_FILENAME);
|
|
623
|
+
}
|
|
624
|
+
/** Take the compaction lock of `dir`. Returns the token, or null. */
|
|
625
|
+
export function acquireCompactLock(dir, now = Date.now()) {
|
|
626
|
+
return withUsageStore(dir, false, null, (store) => acquireHeldLock(store, now));
|
|
627
|
+
}
|
|
628
|
+
/** Take over the lock of `dir` judged stale with content `judged`. Returns the token, or null. */
|
|
629
|
+
export function claimStaleCompactLock(dir, judged, now = Date.now()) {
|
|
630
|
+
return withUsageStore(dir, false, null, (store) => claimStaleLock(store, judged, now));
|
|
631
|
+
}
|
|
632
|
+
/** Give the lock of `dir` back. Does nothing when another process has taken it over. */
|
|
633
|
+
export function releaseCompactLock(dir, token) {
|
|
634
|
+
withUsageStore(dir, false, undefined, (store) => releaseHeldLock(store, token));
|
|
635
|
+
}
|
|
636
|
+
/** Remove stale locks a crashed takeover left aside. */
|
|
637
|
+
function sweepAsideLocks(store, now) {
|
|
638
|
+
const listed = store.list();
|
|
639
|
+
if (!listed.ok)
|
|
640
|
+
return;
|
|
641
|
+
for (const name of listed.value) {
|
|
642
|
+
if (!ASIDE_LOCK_PATTERN.test(name))
|
|
643
|
+
continue;
|
|
644
|
+
const facts = store.stat(name);
|
|
645
|
+
if (facts.ok && now - facts.value.mtimeMs > COMPACT_LOCK_STALE_MS)
|
|
646
|
+
store.remove(name);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Fold the usage file into one line per date, kind and command.
|
|
651
|
+
*
|
|
652
|
+
* One process at a time, behind a lock that a later run takes over after a
|
|
653
|
+
* minute (see {@link acquireHeldLock}). The live file is renamed first, so
|
|
654
|
+
* other hq processes keep appending to a fresh file. The folded lines are
|
|
655
|
+
* then appended to that fresh file with a marker that names the renamed file
|
|
656
|
+
* and how many of its bytes were folded.
|
|
657
|
+
*
|
|
658
|
+
* The renamed file is kept until the next compaction. A process that opened
|
|
659
|
+
* it just before the rename can still write its line there; the next
|
|
660
|
+
* compaction (or `hq doctor usage`) reads what lies past the marked length,
|
|
661
|
+
* and only then is the file removed. A renamed file left by a crash is
|
|
662
|
+
* handled the same way: folded once, by its marker.
|
|
663
|
+
*
|
|
664
|
+
* Every rename, append and removal goes through the store helper, so each
|
|
665
|
+
* runs only while the folder's path still leads to the held folder, and the
|
|
666
|
+
* lock is checked again before the rename and before the append.
|
|
667
|
+
* Returns whether this call compacted.
|
|
668
|
+
*/
|
|
669
|
+
export function compactCommandUsage(dir, now = Date.now()) {
|
|
670
|
+
return withUsageStore(dir, false, false, (store) => compactWithLock(store, now));
|
|
671
|
+
}
|
|
672
|
+
function compactWithLock(store, now) {
|
|
673
|
+
// The lock is timed by the real clock: `now` may be a date under test.
|
|
674
|
+
const lockToken = acquireHeldLock(store, Date.now());
|
|
675
|
+
if (lockToken === null)
|
|
676
|
+
return false;
|
|
677
|
+
try {
|
|
678
|
+
return compactHeld(store, lockToken, now);
|
|
679
|
+
}
|
|
680
|
+
finally {
|
|
681
|
+
releaseHeldLock(store, lockToken);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function compactHeld(store, lockToken, now) {
|
|
685
|
+
// A link (soft or hard), a pipe or a folder at the usage path is left where it is.
|
|
686
|
+
if (!store.stat(COMMAND_USAGE_FILENAME).ok)
|
|
687
|
+
return false;
|
|
688
|
+
// A name no earlier compaction used: a marker counts bytes of one file,
|
|
689
|
+
// so a renamed file must never be replaced by another under the same id.
|
|
690
|
+
const rotated = `usage.${process.pid.toString(36)}-${Date.now().toString(36)}-${randomPart()}.old`;
|
|
691
|
+
if (!holdsCompactLock(store, lockToken))
|
|
692
|
+
return false;
|
|
693
|
+
// Refused when the folder was swapped before the rename, and reported when
|
|
694
|
+
// it was swapped during it; either way this pass stops here.
|
|
695
|
+
if (!store.rename(COMMAND_USAGE_FILENAME, rotated).ok)
|
|
696
|
+
return false;
|
|
697
|
+
const sources = readSources(store, false);
|
|
698
|
+
const offsets = mergedOffsets(sources);
|
|
699
|
+
const block = renderCompacted(collectTotals(sources, offsets), now) +
|
|
700
|
+
sources.map((source) => `${MERGED_MARKER}\t${source.id}\t${source.bytes.length}\n`).join("");
|
|
701
|
+
if (!holdsCompactLock(store, lockToken))
|
|
702
|
+
return false;
|
|
703
|
+
// One write, so a concurrent reader sees the folded lines and their
|
|
704
|
+
// markers together or not at all.
|
|
705
|
+
if (!store.appendLine(COMMAND_USAGE_FILENAME, block).ok)
|
|
706
|
+
return false;
|
|
707
|
+
// Remove the files an earlier compaction renamed: their late lines were
|
|
708
|
+
// folded just now. The file renamed in this pass stays for the next one.
|
|
709
|
+
// A file that grew since the read above stays too; its marker records how
|
|
710
|
+
// much is folded, and the next pass takes the rest. What is left open is a
|
|
711
|
+
// write that lands between the size check and the removal, from a process
|
|
712
|
+
// that has held the file open across two compactions.
|
|
713
|
+
for (const source of sources) {
|
|
714
|
+
if (source.id === null || !offsets.has(source.id))
|
|
715
|
+
continue;
|
|
716
|
+
const facts = store.stat(source.name);
|
|
717
|
+
if (facts.ok && facts.value.size === source.bytes.length)
|
|
718
|
+
store.remove(source.name);
|
|
719
|
+
}
|
|
720
|
+
sweepAsideLocks(store, Date.now());
|
|
721
|
+
return true;
|
|
722
|
+
}
|
|
723
|
+
/** Counts per command for the last {@link COMMAND_USAGE_WINDOW_DAYS} days. */
|
|
724
|
+
export function readCommandUsage(options = {}) {
|
|
725
|
+
const now = options.now ?? Date.now();
|
|
726
|
+
const dir = options.dir === undefined ? commandUsageDir(options.env) : options.dir;
|
|
727
|
+
const from = windowStart(now);
|
|
728
|
+
const to = utcDate(now);
|
|
729
|
+
const rows = new Map();
|
|
730
|
+
let bytes = 0;
|
|
731
|
+
if (dir) {
|
|
732
|
+
const sources = withUsageStore(dir, false, [], (store) => readSources(store, true), options.at);
|
|
733
|
+
bytes = sources.reduce((sum, source) => sum + source.bytes.length, 0);
|
|
734
|
+
for (const [key, count] of collectTotals(sources, mergedOffsets(sources))) {
|
|
735
|
+
const [date, code, command] = key.split("\t");
|
|
736
|
+
if (date < from || date > to)
|
|
737
|
+
continue;
|
|
738
|
+
const row = rows.get(command) ?? { command, runs: 0, stillUseRuns: 0, refused: 0 };
|
|
739
|
+
const kind = CODE_KIND[code];
|
|
740
|
+
if (kind === "run")
|
|
741
|
+
row.runs += count;
|
|
742
|
+
else if (kind === "still-use")
|
|
743
|
+
row.stillUseRuns += count;
|
|
744
|
+
else
|
|
745
|
+
row.refused += count;
|
|
746
|
+
rows.set(command, row);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
const total = (row) => row.runs + row.stillUseRuns + row.refused;
|
|
750
|
+
const commands = [...rows.values()].sort((left, right) => total(right) - total(left) || (left.command < right.command ? -1 : 1));
|
|
751
|
+
return {
|
|
752
|
+
schema: 1,
|
|
753
|
+
windowDays: COMMAND_USAGE_WINDOW_DAYS,
|
|
754
|
+
from,
|
|
755
|
+
to,
|
|
756
|
+
file: dir ? path.join(dir, COMMAND_USAGE_FILENAME) : null,
|
|
757
|
+
bytes,
|
|
758
|
+
leavesThisComputer: false,
|
|
759
|
+
commands,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
/** Plain-text report for `hq doctor usage`. */
|
|
763
|
+
export function renderCommandUsageText(report) {
|
|
764
|
+
const lines = [
|
|
765
|
+
`Commands run on this computer in the last ${report.windowDays} days (${report.from} to ${report.to}, UTC)`,
|
|
766
|
+
"",
|
|
767
|
+
];
|
|
768
|
+
if (report.commands.length === 0) {
|
|
769
|
+
lines.push(" No runs counted yet.");
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
// While the gate is off nothing is refused, so the column is shown only
|
|
773
|
+
// when the gate is on or an older count holds a refused attempt.
|
|
774
|
+
const showRefused = RETIRING_GATE_ENABLED || report.commands.some((row) => row.refused > 0);
|
|
775
|
+
const headers = ["command", "runs", `with ${STILL_USE_FLAG}`, ...(showRefused ? ["refused"] : [])];
|
|
776
|
+
const table = report.commands.map((row) => [
|
|
777
|
+
row.command,
|
|
778
|
+
String(row.runs),
|
|
779
|
+
String(row.stillUseRuns),
|
|
780
|
+
...(showRefused ? [String(row.refused)] : []),
|
|
781
|
+
]);
|
|
782
|
+
const widths = headers.map((header, column) => Math.max(header.length, ...table.map((cells) => cells[column].length)));
|
|
783
|
+
const format = (cells) => ` ${cells
|
|
784
|
+
.map((cell, column) => (column === 0 ? cell.padEnd(widths[column]) : cell.padStart(widths[column])))
|
|
785
|
+
.join(" ")}`.trimEnd();
|
|
786
|
+
lines.push(format(headers), ...table.map(format));
|
|
787
|
+
}
|
|
788
|
+
lines.push("");
|
|
789
|
+
if (report.file) {
|
|
790
|
+
lines.push(`Kept in ${report.file} (${report.bytes} bytes): the command name and the date of each run, never arguments or values.`, "It never leaves this computer: it is not sent, synced, or attached to feedback, and HQ_TELEMETRY=0 does not turn it off.", `Delete the ${COMMAND_USAGE_DIRNAME} folder to clear it.`);
|
|
791
|
+
}
|
|
792
|
+
else {
|
|
793
|
+
lines.push("This run keeps no count.");
|
|
794
|
+
}
|
|
795
|
+
return `${lines.join("\n")}\n`;
|
|
796
|
+
}
|
|
797
|
+
//# sourceMappingURL=command-usage.js.map
|