@primitive.ai/prim 0.1.0-alpha.73 → 0.1.0-alpha.75

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/dist/index.js CHANGED
@@ -149,85 +149,22 @@ import { fileURLToPath as fileURLToPath2 } from "url";
149
149
  import { Command } from "commander";
150
150
  import updateNotifier from "update-notifier";
151
151
 
152
- // src/commands/activation.ts
153
- async function applyActivation(active) {
154
- const root = gitToplevel();
155
- if (!root) {
156
- process.stderr.write(
157
- `[prim] not a git repository \u2014 run \`prim ${active ? "enable" : "disable"}\` inside a repo
158
- `
159
- );
160
- process.exit(1);
161
- }
162
- let phase = active ? "post-commit hook coverage" : "local deactivation";
152
+ // src/lib/confirmation.ts
153
+ function isNonInteractive(globals) {
154
+ return Boolean(globals.nonInteractive || process.env.CI || process.env.PRIM_NON_INTERACTIVE);
155
+ }
156
+ async function askConfirmation(question, output = process.stdout) {
157
+ if (!process.stdin.isTTY) return false;
158
+ const { createInterface } = await import("readline/promises");
159
+ const rl = createInterface({ input: process.stdin, output });
163
160
  try {
164
- let binding;
165
- let postCommitHook;
166
- let postRewriteHook;
167
- if (active) {
168
- postCommitHook = ensureEffectivePostCommitHook(root).path;
169
- try {
170
- postRewriteHook = ensureEffectivePostRewriteHook(root).path;
171
- } catch (error) {
172
- const detail = error instanceof Error ? error.message : String(error);
173
- process.stderr.write(`[prim] post-rewrite hook coverage is degraded: ${detail}
174
- `);
175
- }
176
- phase = "repository binding";
177
- binding = await bindRepository(root);
178
- phase = "local activation";
179
- }
180
- setRepoActive(root, active);
181
- await daemonRequest("statusline_invalidate", {}, { timeoutMs: 250 });
182
- if (binding?.status === "unbound") {
183
- process.stderr.write(`[prim] Prim is enabled locally in ${root}
184
- `);
185
- process.stderr.write(
186
- "[prim] repository is not connected to Primitive; Moves still ingest into the team graph without repository-specific file attribution, Conflict Gate verification, or commit correlation\n"
187
- );
188
- process.stderr.write(
189
- `[prim] ask an organization owner or administrator to grant Primitive's GitHub App access to this repository through Primitive's GitHub App onboarding; binding retries automatically at the next agent SessionStart
190
- `
191
- );
192
- } else {
193
- process.stderr.write(`[prim] prim ${active ? "enabled" : "disabled"} in ${root}
194
- `);
195
- }
196
- printJson({
197
- active,
198
- repo: root,
199
- ...binding ? {
200
- bindingStatus: binding.status,
201
- repositoryFullName: binding.repositoryFullName,
202
- ...binding.status === "connected" ? { repoSyncId: binding.repoSyncId } : {}
203
- } : {},
204
- ...postCommitHook ? { postCommitHook } : {},
205
- ...postRewriteHook ? { postRewriteHook } : {}
206
- });
207
- } catch (err) {
208
- const detail = err instanceof Error ? err.message : String(err);
209
- process.stderr.write(
210
- active ? `[prim] failed to enable prim during ${phase}: ${detail}
211
- ` : `[prim] failed to disable prim: ${detail}
212
- `
213
- );
214
- process.exit(1);
161
+ const answer = await rl.question(`${question} [y/N] `);
162
+ const normalized = answer.trim().toLowerCase();
163
+ return normalized === "y" || normalized === "yes";
164
+ } finally {
165
+ rl.close();
215
166
  }
216
167
  }
217
- function registerActivationCommands(program2) {
218
- program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").action(() => applyActivation(true));
219
- program2.command("disable").description("Mute prim's hooks in this repo (git config prim.active=false)").action(() => applyActivation(false));
220
- }
221
-
222
- // src/commands/auth.ts
223
- import { execFile } from "child_process";
224
- import { createHash, randomBytes as randomBytes2 } from "crypto";
225
- import { existsSync, readFileSync } from "fs";
226
- import { createServer } from "http";
227
- import { platform } from "os";
228
-
229
- // src/auth/api-keys.ts
230
- import { randomBytes } from "crypto";
231
168
 
232
169
  // src/generated/cli-http-v1.validators.js
233
170
  var import_ucs2length = __toESM(require_ucs2length(), 1);
@@ -9961,7 +9898,113 @@ function isGitHubInstallIntentStatusResponse(value) {
9961
9898
  }
9962
9899
  }
9963
9900
 
9901
+ // src/lib/github-install-intent.ts
9902
+ var PROTOCOL_VERSION = 1;
9903
+ var MODE = "install_intent_v1";
9904
+ var START_PATH = "/api/cli/github/install-intents";
9905
+ var POLL_REQUEST_TIMEOUT_MS = 1e4;
9906
+ var MAX_INTENT_LIFETIME_MS = 15 * 6e4;
9907
+ var REPOSITORY_IDENTITY_MIGRATION_REQUIRED = "repository_identity_migration_required";
9908
+ function isRepositoryIdentityMigrationRequiredStatus(value) {
9909
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
9910
+ return false;
9911
+ }
9912
+ const record2 = value;
9913
+ if (record2.failureCode !== REPOSITORY_IDENTITY_MIGRATION_REQUIRED) {
9914
+ return false;
9915
+ }
9916
+ return isGitHubInstallIntentStatusResponse({
9917
+ ...record2,
9918
+ failureCode: "proof_commit_failed"
9919
+ });
9920
+ }
9921
+ function parseGitHubInstallIntentStart(value, now = Date.now()) {
9922
+ if (!isGitHubInstallIntentStartResponse(value) || value.expiresAt <= now || value.expiresAt - now > MAX_INTENT_LIFETIME_MS) {
9923
+ return null;
9924
+ }
9925
+ return value;
9926
+ }
9927
+ function parseGitHubInstallIntentStatus(value, expectedExpiresAt) {
9928
+ if (isGitHubInstallIntentStatusResponse(value)) {
9929
+ return value.expiresAt === expectedExpiresAt ? value : null;
9930
+ }
9931
+ if (!isRepositoryIdentityMigrationRequiredStatus(value) || value.expiresAt !== expectedExpiresAt) {
9932
+ return null;
9933
+ }
9934
+ return value;
9935
+ }
9936
+ async function createGitHubInstallIntent(client, options = {}) {
9937
+ const { now = Date.now, ...requestOptions } = options;
9938
+ const raw = await client.post(START_PATH, void 0, requestOptions);
9939
+ const parsed = parseGitHubInstallIntentStart(raw, now());
9940
+ if (!parsed) throw new Error("server returned an invalid GitHub install-intent response");
9941
+ return parsed;
9942
+ }
9943
+ function defaultSleep(milliseconds, signal) {
9944
+ if (signal.aborted) return Promise.reject(signal.reason);
9945
+ return new Promise((resolvePromise, reject) => {
9946
+ const onAbort = () => {
9947
+ clearTimeout(timer);
9948
+ reject(signal.reason);
9949
+ };
9950
+ const timer = setTimeout(() => {
9951
+ signal.removeEventListener("abort", onAbort);
9952
+ resolvePromise();
9953
+ }, milliseconds);
9954
+ signal.addEventListener("abort", onAbort, { once: true });
9955
+ });
9956
+ }
9957
+ function expiredStatus(start) {
9958
+ return {
9959
+ protocolVersion: PROTOCOL_VERSION,
9960
+ mode: MODE,
9961
+ found: true,
9962
+ status: "expired",
9963
+ expiresAt: start.expiresAt,
9964
+ closedAt: start.expiresAt
9965
+ };
9966
+ }
9967
+ async function pollGitHubInstallIntent(client, start, options = {}) {
9968
+ const now = options.now ?? Date.now;
9969
+ const sleep2 = options.sleep ?? defaultSleep;
9970
+ const signal = options.signal ?? new AbortController().signal;
9971
+ const path = `${START_PATH}/${encodeURIComponent(start.intentId)}`;
9972
+ while (true) {
9973
+ if (signal.aborted) throw signal.reason;
9974
+ const remainingBeforeSleep = start.expiresAt - now();
9975
+ if (remainingBeforeSleep <= 0) return expiredStatus(start);
9976
+ await sleep2(Math.min(start.pollAfterMs, remainingBeforeSleep), signal);
9977
+ if (signal.aborted) throw signal.reason;
9978
+ const remainingBeforeRequest = start.expiresAt - now();
9979
+ if (remainingBeforeRequest <= 0) return expiredStatus(start);
9980
+ let raw;
9981
+ try {
9982
+ raw = await client.get(path, {
9983
+ signal: AbortSignal.any([
9984
+ signal,
9985
+ AbortSignal.timeout(Math.min(POLL_REQUEST_TIMEOUT_MS, remainingBeforeRequest))
9986
+ ])
9987
+ });
9988
+ } catch (error) {
9989
+ if (signal.aborted) throw error;
9990
+ if (now() >= start.expiresAt) return expiredStatus(start);
9991
+ throw error;
9992
+ }
9993
+ const status = parseGitHubInstallIntentStatus(raw, start.expiresAt);
9994
+ if (!status) throw new Error("server returned an invalid GitHub install-intent status");
9995
+ if (status.status !== "pending" && status.status !== "claimed") return status;
9996
+ }
9997
+ }
9998
+
9999
+ // src/commands/auth.ts
10000
+ import { execFile } from "child_process";
10001
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
10002
+ import { existsSync, readFileSync } from "fs";
10003
+ import { createServer } from "http";
10004
+ import { platform } from "os";
10005
+
9964
10006
  // src/auth/api-keys.ts
10007
+ import { randomBytes } from "crypto";
9965
10008
  var USER_API_KEY_TIMEOUT_MS = 1e4;
9966
10009
  var USER_API_KEY_EXIT = {
9967
10010
  ok: 0,
@@ -10850,66 +10893,291 @@ async function exchangeCode(siteUrl, code, codeVerifier, redirectUri) {
10850
10893
  };
10851
10894
  }
10852
10895
 
10853
- // src/commands/claude-install.ts
10854
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
10855
- import { homedir } from "os";
10856
- import { join as join2 } from "path";
10857
-
10858
- // src/lib/hook-runtime.ts
10859
- import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
10860
- import {
10861
- constants,
10862
- accessSync,
10863
- chmodSync,
10864
- copyFileSync,
10865
- existsSync as existsSync2,
10866
- lstatSync,
10867
- mkdirSync,
10868
- mkdtempSync,
10869
- readFileSync as readFileSync2,
10870
- readdirSync,
10871
- realpathSync,
10872
- renameSync,
10873
- rmSync,
10874
- statSync,
10875
- utimesSync,
10876
- writeFileSync
10877
- } from "fs";
10878
- import { dirname, isAbsolute, join, resolve } from "path";
10879
- var HOOK_RUNTIME_SCHEMA_VERSION = 1;
10880
- var DIRECTORY_MODE = 448;
10881
- var DATA_FILE_MODE = 384;
10882
- var LAUNCHER_MODE = 448;
10883
- var RELEASE_PREFIX = "release-";
10884
- var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
10885
- var MAX_MANIFEST_BYTES = 64 * 1024;
10886
- var MAX_RELEASES = 8;
10887
- var MAX_RELEASE_DELETIONS_PER_STAGE = 8;
10888
- var RETAIN_PREDECESSORS = 2;
10889
- var RELEASE_GRACE_MS = 10 * 60 * 1e3;
10890
- var HOOK_RUNTIME_ENTRIES = {
10891
- // SessionStart self-healing resolves this exact CLI entry to run
10892
- // `daemon ensure`; it must travel with the immutable hook release.
10893
- prim: "dist/index.js",
10894
- "prim-hook": "dist/hooks/prim-hook.js",
10895
- "prim-pre-commit": "dist/hooks/pre-commit.js",
10896
- "prim-post-commit": "dist/hooks/post-commit.js",
10897
- "prim-post-rewrite": "dist/hooks/post-rewrite.js",
10898
- "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
10899
- "prim-post-tool-use": "dist/hooks/post-tool-use.js",
10900
- "prim-session-start": "dist/hooks/session-start.js",
10901
- "prim-session-end": "dist/hooks/session-end.js",
10902
- "prim-daemon-server": "dist/daemon/server.js",
10903
- "prim-statusline": "dist/statusline-main.js"
10896
+ // src/commands/github.ts
10897
+ var BIND_TIMEOUT_MS = 1e4;
10898
+ var START_TIMEOUT_MS = 1e4;
10899
+ var EXIT_OK2 = 0;
10900
+ var EXIT_FAILURE = 1;
10901
+ var EXIT_UNBOUND = 2;
10902
+ var defaultDependencies2 = {
10903
+ cwd: () => process.cwd(),
10904
+ gitToplevel,
10905
+ bindRepositoryWithClient,
10906
+ getPinnedClient,
10907
+ createInstallIntent: createGitHubInstallIntent,
10908
+ pollInstallIntent: pollGitHubInstallIntent,
10909
+ openBrowser,
10910
+ now: Date.now
10904
10911
  };
10905
- var SOURCE_ENTRIES = Object.fromEntries(
10906
- Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
10907
- bin,
10908
- target.replace(/^dist\//u, "")
10909
- ])
10910
- );
10911
- function hookRuntimePaths(options = {}) {
10912
- const env = options.env ?? process.env;
10912
+ function errorMessage(error) {
10913
+ return error instanceof Error ? error.message : String(error);
10914
+ }
10915
+ function reportConnectFailure(error) {
10916
+ const message = errorMessage(error);
10917
+ const human = boundedHealthError(message) ?? "unknown error";
10918
+ process.stderr.write(`[prim] github connect failed: ${human}
10919
+ `);
10920
+ printJson({
10921
+ status: "error",
10922
+ error: message,
10923
+ ...error instanceof HttpError ? { httpStatus: error.status } : {}
10924
+ });
10925
+ process.exitCode = EXIT_FAILURE;
10926
+ }
10927
+ function reportBinding(binding, installAttempted = false) {
10928
+ if (binding.status === "connected") {
10929
+ process.stderr.write(
10930
+ `[prim] repository binding connected for GitHub origin ${binding.repositoryFullName}
10931
+ `
10932
+ );
10933
+ printJson(binding);
10934
+ process.exitCode = EXIT_OK2;
10935
+ return;
10936
+ }
10937
+ process.stderr.write(
10938
+ installAttempted ? `[prim] GitHub installation completed, but ${binding.repositoryFullName} was not granted admin access; repository binding remains unbound
10939
+ ` : `[prim] repository binding unbound for GitHub origin ${binding.repositoryFullName}; starting GitHub App installation
10940
+ `
10941
+ );
10942
+ printJson(binding);
10943
+ process.exitCode = EXIT_UNBOUND;
10944
+ }
10945
+ function terminalInstallError(status) {
10946
+ if (status.status === "failed_terminal") {
10947
+ return new Error(`GitHub installation failed: ${status.failureCode}`);
10948
+ }
10949
+ return new Error(`GitHub installation ${status.status}`);
10950
+ }
10951
+ async function completeInstallIntent(client, start, dependencies, browser) {
10952
+ process.stderr.write(`[prim] complete GitHub App installation at:
10953
+ ${start.browserUrl}
10954
+ `);
10955
+ if (browser) dependencies.openBrowser(start.browserUrl);
10956
+ return dependencies.pollInstallIntent(client, start, {
10957
+ now: dependencies.now
10958
+ });
10959
+ }
10960
+ async function runGithubConnect(dependencies = defaultDependencies2, options = {}) {
10961
+ const root = options.root ?? dependencies.gitToplevel(dependencies.cwd());
10962
+ if (!root) return { kind: "not-a-repo" };
10963
+ try {
10964
+ const client = await dependencies.getPinnedClient({
10965
+ signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
10966
+ });
10967
+ const existing = await dependencies.bindRepositoryWithClient(root, client, {
10968
+ signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
10969
+ });
10970
+ if (existing.status === "connected") {
10971
+ return { kind: "connected", binding: existing };
10972
+ }
10973
+ const start = await dependencies.createInstallIntent(client, {
10974
+ signal: AbortSignal.timeout(START_TIMEOUT_MS),
10975
+ now: dependencies.now
10976
+ });
10977
+ const status = await completeInstallIntent(
10978
+ client,
10979
+ start,
10980
+ dependencies,
10981
+ options.browser ?? true
10982
+ );
10983
+ if (status.status !== "consumed") throw terminalInstallError(status);
10984
+ process.stderr.write(
10985
+ `[prim] GitHub installation verified: ${status.adminRepositoryCount} admin repositories (${status.repositoryCount} total)
10986
+ `
10987
+ );
10988
+ const binding = await dependencies.bindRepositoryWithClient(root, client, {
10989
+ signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
10990
+ });
10991
+ return binding.status === "connected" ? { kind: "connected", binding } : { kind: "unbound", binding, installAttempted: true };
10992
+ } catch (error) {
10993
+ return { kind: "error", error };
10994
+ }
10995
+ }
10996
+ async function performGithubConnect(dependencies = defaultDependencies2, options = {}) {
10997
+ const outcome = await runGithubConnect(dependencies, options);
10998
+ switch (outcome.kind) {
10999
+ case "not-a-repo":
11000
+ reportConnectFailure(
11001
+ new Error("not a git repository \u2014 run `prim github connect` inside a GitHub repository")
11002
+ );
11003
+ return;
11004
+ case "error":
11005
+ reportConnectFailure(outcome.error);
11006
+ return;
11007
+ case "connected":
11008
+ reportBinding(outcome.binding);
11009
+ return;
11010
+ case "unbound":
11011
+ reportBinding(outcome.binding, outcome.installAttempted);
11012
+ return;
11013
+ }
11014
+ }
11015
+ function registerGithubCommands(program2, dependencies = defaultDependencies2) {
11016
+ const github = program2.command("github").description("Manage GitHub repository bindings");
11017
+ github.command("connect").description("Install or reuse the Primitive GitHub App and bind the current GitHub origin").option("--no-browser", "Print the GitHub installation URL without opening a browser").action(async (options, command) => {
11018
+ const globals = command.optsWithGlobals();
11019
+ await performGithubConnect(dependencies, {
11020
+ browser: options.browser && globals.nonInteractive !== true
11021
+ });
11022
+ });
11023
+ }
11024
+
11025
+ // src/commands/activation.ts
11026
+ var CONNECT_PROMPT = "[prim] Connect this repository to Primitive via the GitHub App now?";
11027
+ async function maybeConnectRepository(root, globals) {
11028
+ if (isNonInteractive(globals)) return void 0;
11029
+ const approved = Boolean(globals.yes) || await askConfirmation(CONNECT_PROMPT, process.stderr);
11030
+ if (!approved) return void 0;
11031
+ const outcome = await runGithubConnect(void 0, { root, browser: true });
11032
+ if (outcome.kind === "connected") {
11033
+ process.stderr.write(
11034
+ `[prim] repository binding connected for GitHub origin ${outcome.binding.repositoryFullName}
11035
+ `
11036
+ );
11037
+ return outcome.binding;
11038
+ }
11039
+ if (outcome.kind === "error") {
11040
+ const detail = outcome.error instanceof Error ? outcome.error.message : String(outcome.error);
11041
+ process.stderr.write(`[prim] connect could not complete: ${detail}
11042
+ `);
11043
+ }
11044
+ return void 0;
11045
+ }
11046
+ async function applyActivation(active, globals = {}) {
11047
+ const root = gitToplevel();
11048
+ if (!root) {
11049
+ process.stderr.write(
11050
+ `[prim] not a git repository \u2014 run \`prim ${active ? "enable" : "disable"}\` inside a repo
11051
+ `
11052
+ );
11053
+ process.exit(1);
11054
+ }
11055
+ let phase = active ? "post-commit hook coverage" : "local deactivation";
11056
+ try {
11057
+ let binding;
11058
+ let postCommitHook;
11059
+ let postRewriteHook;
11060
+ if (active) {
11061
+ postCommitHook = ensureEffectivePostCommitHook(root).path;
11062
+ try {
11063
+ postRewriteHook = ensureEffectivePostRewriteHook(root).path;
11064
+ } catch (error) {
11065
+ const detail = error instanceof Error ? error.message : String(error);
11066
+ process.stderr.write(`[prim] post-rewrite hook coverage is degraded: ${detail}
11067
+ `);
11068
+ }
11069
+ phase = "repository binding";
11070
+ binding = await bindRepository(root);
11071
+ phase = "local activation";
11072
+ }
11073
+ setRepoActive(root, active);
11074
+ if (active && binding?.status === "unbound") {
11075
+ const connected = await maybeConnectRepository(root, globals);
11076
+ if (connected) binding = connected;
11077
+ }
11078
+ await daemonRequest("statusline_invalidate", {}, { timeoutMs: 250 });
11079
+ if (binding?.status === "unbound") {
11080
+ process.stderr.write(`[prim] Prim is enabled locally in ${root}
11081
+ `);
11082
+ process.stderr.write(
11083
+ "[prim] repository is not connected to Primitive; Moves still ingest into the team graph without repository-specific file attribution, Conflict Gate verification, or commit correlation\n"
11084
+ );
11085
+ process.stderr.write(
11086
+ `[prim] ask an organization owner or administrator to grant Primitive's GitHub App access to this repository through Primitive's GitHub App onboarding; binding retries automatically at the next agent SessionStart
11087
+ `
11088
+ );
11089
+ } else {
11090
+ process.stderr.write(`[prim] prim ${active ? "enabled" : "disabled"} in ${root}
11091
+ `);
11092
+ }
11093
+ printJson({
11094
+ active,
11095
+ repo: root,
11096
+ ...binding ? {
11097
+ bindingStatus: binding.status,
11098
+ repositoryFullName: binding.repositoryFullName,
11099
+ ...binding.status === "connected" ? { repoSyncId: binding.repoSyncId } : {}
11100
+ } : {},
11101
+ ...postCommitHook ? { postCommitHook } : {},
11102
+ ...postRewriteHook ? { postRewriteHook } : {}
11103
+ });
11104
+ } catch (err) {
11105
+ const detail = err instanceof Error ? err.message : String(err);
11106
+ process.stderr.write(
11107
+ active ? `[prim] failed to enable prim during ${phase}: ${detail}
11108
+ ` : `[prim] failed to disable prim: ${detail}
11109
+ `
11110
+ );
11111
+ process.exit(1);
11112
+ }
11113
+ }
11114
+ function registerActivationCommands(program2) {
11115
+ program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").action((_opts, command) => applyActivation(true, command.optsWithGlobals()));
11116
+ program2.command("disable").description("Mute prim's hooks in this repo (git config prim.active=false)").action(
11117
+ (_opts, command) => applyActivation(false, command.optsWithGlobals())
11118
+ );
11119
+ }
11120
+
11121
+ // src/commands/claude-install.ts
11122
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
11123
+ import { homedir } from "os";
11124
+ import { join as join2 } from "path";
11125
+
11126
+ // src/lib/hook-runtime.ts
11127
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
11128
+ import {
11129
+ constants,
11130
+ accessSync,
11131
+ chmodSync,
11132
+ copyFileSync,
11133
+ existsSync as existsSync2,
11134
+ lstatSync,
11135
+ mkdirSync,
11136
+ mkdtempSync,
11137
+ readFileSync as readFileSync2,
11138
+ readdirSync,
11139
+ realpathSync,
11140
+ renameSync,
11141
+ rmSync,
11142
+ statSync,
11143
+ utimesSync,
11144
+ writeFileSync
11145
+ } from "fs";
11146
+ import { dirname, isAbsolute, join, resolve } from "path";
11147
+ var HOOK_RUNTIME_SCHEMA_VERSION = 1;
11148
+ var DIRECTORY_MODE = 448;
11149
+ var DATA_FILE_MODE = 384;
11150
+ var LAUNCHER_MODE = 448;
11151
+ var RELEASE_PREFIX = "release-";
11152
+ var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
11153
+ var MAX_MANIFEST_BYTES = 64 * 1024;
11154
+ var MAX_RELEASES = 8;
11155
+ var MAX_RELEASE_DELETIONS_PER_STAGE = 8;
11156
+ var RETAIN_PREDECESSORS = 2;
11157
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
11158
+ var HOOK_RUNTIME_ENTRIES = {
11159
+ // SessionStart self-healing resolves this exact CLI entry to run
11160
+ // `daemon ensure`; it must travel with the immutable hook release.
11161
+ prim: "dist/index.js",
11162
+ "prim-hook": "dist/hooks/prim-hook.js",
11163
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
11164
+ "prim-post-commit": "dist/hooks/post-commit.js",
11165
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
11166
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
11167
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
11168
+ "prim-session-start": "dist/hooks/session-start.js",
11169
+ "prim-session-end": "dist/hooks/session-end.js",
11170
+ "prim-daemon-server": "dist/daemon/server.js",
11171
+ "prim-statusline": "dist/statusline-main.js"
11172
+ };
11173
+ var SOURCE_ENTRIES = Object.fromEntries(
11174
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
11175
+ bin,
11176
+ target.replace(/^dist\//u, "")
11177
+ ])
11178
+ );
11179
+ function hookRuntimePaths(options = {}) {
11180
+ const env = options.env ?? process.env;
10913
11181
  const configDir = primConfigDirectory({
10914
11182
  ...options,
10915
11183
  env,
@@ -12652,7 +12920,7 @@ function atomicWrite2(path, content, mode, validate) {
12652
12920
  }
12653
12921
  return true;
12654
12922
  }
12655
- function defaultSleep(ms) {
12923
+ function defaultSleep2(ms) {
12656
12924
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
12657
12925
  }
12658
12926
  function validatePlist(path, timeoutMs2) {
@@ -12971,7 +13239,7 @@ async function ensureMacDaemonLocked(options) {
12971
13239
  PLIST_FILE_MODE,
12972
13240
  options.validatePlist ?? validatePlist
12973
13241
  );
12974
- const sleep2 = options.sleep ?? defaultSleep;
13242
+ const sleep2 = options.sleep ?? defaultSleep2;
12975
13243
  const nowMs = options.nowMs ?? performance.now.bind(performance);
12976
13244
  const deadlineMs = nowMs() + TRANSITION_TIMEOUT_MS;
12977
13245
  const inspect = options.inspectDaemon ?? inspectDaemon;
@@ -13025,7 +13293,7 @@ async function bootoutMacDaemon(options = {}) {
13025
13293
  async function bootoutMacDaemonLocked(options) {
13026
13294
  const runner = options.runner ?? runLaunchctl;
13027
13295
  const inspect = options.inspectDaemon ?? inspectDaemon;
13028
- const sleep2 = options.sleep ?? defaultSleep;
13296
+ const sleep2 = options.sleep ?? defaultSleep2;
13029
13297
  const nowMs = options.nowMs ?? performance.now.bind(performance);
13030
13298
  const deadlineMs = nowMs() + TRANSITION_TIMEOUT_MS;
13031
13299
  const paths = launchdPaths(options);
@@ -13095,7 +13363,7 @@ var READY_POLL_MS2 = 100;
13095
13363
  var READY_PROBE_TIMEOUT_MS2 = 250;
13096
13364
  var HEALTHY_TIMEOUT_MS = 3e4;
13097
13365
  var HEALTHY_POLL_MS = 250;
13098
- var EXIT_OK2 = 0;
13366
+ var EXIT_OK3 = 0;
13099
13367
  var EXIT_NOT_RUNNING = 2;
13100
13368
  var EXIT_BOOTING = 3;
13101
13369
  function formatDaemonLifecycleMessage(message, decisionIngestion) {
@@ -13476,7 +13744,7 @@ function classifyStatus(pidAlive, responding, snapshot, pid) {
13476
13744
  };
13477
13745
  }
13478
13746
  if (!snapshot) {
13479
- return { json: { running: true, responding: true }, exitCode: EXIT_OK2 };
13747
+ return { json: { running: true, responding: true }, exitCode: EXIT_OK3 };
13480
13748
  }
13481
13749
  if (snapshot.healthy === false) {
13482
13750
  return {
@@ -13484,7 +13752,7 @@ function classifyStatus(pidAlive, responding, snapshot, pid) {
13484
13752
  exitCode: EXIT_BOOTING
13485
13753
  };
13486
13754
  }
13487
- return { json: { running: true, responding: true, ...snapshot }, exitCode: EXIT_OK2 };
13755
+ return { json: { running: true, responding: true, ...snapshot }, exitCode: EXIT_OK3 };
13488
13756
  }
13489
13757
  function classifyLaunchdStatus(service, responding, snapshot, disabled) {
13490
13758
  if (!service) {
@@ -13582,7 +13850,7 @@ function classifyLaunchdStatus(service, responding, snapshot, disabled) {
13582
13850
  disabled,
13583
13851
  ...snapshot
13584
13852
  },
13585
- exitCode: EXIT_OK2
13853
+ exitCode: EXIT_OK3
13586
13854
  };
13587
13855
  }
13588
13856
  function formatDaemonSnapshotMessage(snapshot, supervised, decisionIngestion, bindingState) {
@@ -13632,7 +13900,7 @@ async function detachedDaemonStatus() {
13632
13900
  writeLiveSnapshot(snapshot);
13633
13901
  }
13634
13902
  console.log(JSON.stringify(json, null, 2));
13635
- if (exitCode !== EXIT_OK2 && !process.exitCode) {
13903
+ if (exitCode !== EXIT_OK3 && !process.exitCode) {
13636
13904
  process.exitCode = exitCode;
13637
13905
  }
13638
13906
  }
@@ -13682,7 +13950,7 @@ async function macDaemonStatus() {
13682
13950
  writeLiveSnapshot(snapshot, true);
13683
13951
  }
13684
13952
  console.log(JSON.stringify(json, null, 2));
13685
- if (exitCode !== EXIT_OK2 && !process.exitCode) process.exitCode = exitCode;
13953
+ if (exitCode !== EXIT_OK3 && !process.exitCode) process.exitCode = exitCode;
13686
13954
  }
13687
13955
  async function daemonStatus() {
13688
13956
  if (process.platform === "darwin") {
@@ -14278,7 +14546,7 @@ var DECISION_LIFECYCLE_EXIT = {
14278
14546
  server: 3,
14279
14547
  notFound: 4
14280
14548
  };
14281
- var defaultDependencies2 = {
14549
+ var defaultDependencies3 = {
14282
14550
  getClient,
14283
14551
  signal: () => AbortSignal.timeout(DECISION_LIFECYCLE_TIMEOUT_MS),
14284
14552
  writeStdout: (value) => console.log(value),
@@ -14491,19 +14759,19 @@ async function executeLifecycle(operation, request, dependencies) {
14491
14759
  return writeFailure2(operation, classifyError2(error), dependencies);
14492
14760
  }
14493
14761
  }
14494
- function publishDecision(id, dependencies = defaultDependencies2) {
14762
+ function publishDecision(id, dependencies = defaultDependencies3) {
14495
14763
  const request = { id };
14496
14764
  return executeLifecycle("publish", request, dependencies);
14497
14765
  }
14498
- function restoreDecision(id, dependencies = defaultDependencies2) {
14766
+ function restoreDecision(id, dependencies = defaultDependencies3) {
14499
14767
  const request = { id };
14500
14768
  return executeLifecycle("restore", request, dependencies);
14501
14769
  }
14502
- function ratifyDecision(id, dependencies = defaultDependencies2) {
14770
+ function ratifyDecision(id, dependencies = defaultDependencies3) {
14503
14771
  const request = { id };
14504
14772
  return executeLifecycle("ratify", request, dependencies);
14505
14773
  }
14506
- function supersedeDecision(id, by, dependencies = defaultDependencies2) {
14774
+ function supersedeDecision(id, by, dependencies = defaultDependencies3) {
14507
14775
  const request = { id, by };
14508
14776
  return executeLifecycle("supersede", request, dependencies);
14509
14777
  }
@@ -15254,26 +15522,9 @@ function formatShowJson(result) {
15254
15522
  return JSON.stringify(result, null, 2);
15255
15523
  }
15256
15524
 
15257
- // src/lib/confirmation.ts
15258
- function isNonInteractive(globals) {
15259
- return Boolean(globals.nonInteractive || process.env.CI || process.env.PRIM_NON_INTERACTIVE);
15260
- }
15261
- async function askConfirmation(question, output = process.stdout) {
15262
- if (!process.stdin.isTTY) return false;
15263
- const { createInterface } = await import("readline/promises");
15264
- const rl = createInterface({ input: process.stdin, output });
15265
- try {
15266
- const answer = await rl.question(`${question} [y/N] `);
15267
- const normalized = answer.trim().toLowerCase();
15268
- return normalized === "y" || normalized === "yes";
15269
- } finally {
15270
- rl.close();
15271
- }
15272
- }
15273
-
15274
15525
  // src/commands/decisions.ts
15275
15526
  var EXIT_NOT_FOUND = 4;
15276
- var EXIT_FAILURE = 1;
15527
+ var EXIT_FAILURE2 = 1;
15277
15528
  var EXIT_USAGE = 2;
15278
15529
  function handleRepairCommandError(error) {
15279
15530
  if (error instanceof RepairProposalNotFoundError) {
@@ -15290,12 +15541,12 @@ function handleRepairCommandError(error) {
15290
15541
  console.error(
15291
15542
  `[prim] ${error instanceof RepairAuthorizationError ? error.message : "Not authorized to review commit repairs; active organization membership and current repository authorization are required"}`
15292
15543
  );
15293
- process.exitCode = EXIT_FAILURE;
15544
+ process.exitCode = EXIT_FAILURE2;
15294
15545
  return true;
15295
15546
  }
15296
15547
  if (error instanceof RepairEndpointVersionError || error instanceof RepairListContractError) {
15297
15548
  console.error(`[prim] ${error.message}`);
15298
- process.exitCode = EXIT_FAILURE;
15549
+ process.exitCode = EXIT_FAILURE2;
15299
15550
  return true;
15300
15551
  }
15301
15552
  return false;
@@ -16927,203 +17178,6 @@ function registerDoctorCommands(program2) {
16927
17178
  });
16928
17179
  }
16929
17180
 
16930
- // src/lib/github-install-intent.ts
16931
- var PROTOCOL_VERSION = 1;
16932
- var MODE = "install_intent_v1";
16933
- var START_PATH = "/api/cli/github/install-intents";
16934
- var POLL_REQUEST_TIMEOUT_MS = 1e4;
16935
- var MAX_INTENT_LIFETIME_MS = 15 * 6e4;
16936
- function parseGitHubInstallIntentStart(value, now = Date.now()) {
16937
- if (!isGitHubInstallIntentStartResponse(value) || value.expiresAt <= now || value.expiresAt - now > MAX_INTENT_LIFETIME_MS) {
16938
- return null;
16939
- }
16940
- return value;
16941
- }
16942
- function parseGitHubInstallIntentStatus(value, expectedExpiresAt) {
16943
- if (!isGitHubInstallIntentStatusResponse(value) || value.expiresAt !== expectedExpiresAt) {
16944
- return null;
16945
- }
16946
- return value;
16947
- }
16948
- async function createGitHubInstallIntent(client, options = {}) {
16949
- const { now = Date.now, ...requestOptions } = options;
16950
- const raw = await client.post(START_PATH, void 0, requestOptions);
16951
- const parsed = parseGitHubInstallIntentStart(raw, now());
16952
- if (!parsed) throw new Error("server returned an invalid GitHub install-intent response");
16953
- return parsed;
16954
- }
16955
- function defaultSleep2(milliseconds, signal) {
16956
- if (signal.aborted) return Promise.reject(signal.reason);
16957
- return new Promise((resolvePromise, reject) => {
16958
- const onAbort = () => {
16959
- clearTimeout(timer);
16960
- reject(signal.reason);
16961
- };
16962
- const timer = setTimeout(() => {
16963
- signal.removeEventListener("abort", onAbort);
16964
- resolvePromise();
16965
- }, milliseconds);
16966
- signal.addEventListener("abort", onAbort, { once: true });
16967
- });
16968
- }
16969
- function expiredStatus(start) {
16970
- return {
16971
- protocolVersion: PROTOCOL_VERSION,
16972
- mode: MODE,
16973
- found: true,
16974
- status: "expired",
16975
- expiresAt: start.expiresAt,
16976
- closedAt: start.expiresAt
16977
- };
16978
- }
16979
- async function pollGitHubInstallIntent(client, start, options = {}) {
16980
- const now = options.now ?? Date.now;
16981
- const sleep2 = options.sleep ?? defaultSleep2;
16982
- const signal = options.signal ?? new AbortController().signal;
16983
- const path = `${START_PATH}/${encodeURIComponent(start.intentId)}`;
16984
- while (true) {
16985
- if (signal.aborted) throw signal.reason;
16986
- const remainingBeforeSleep = start.expiresAt - now();
16987
- if (remainingBeforeSleep <= 0) return expiredStatus(start);
16988
- await sleep2(Math.min(start.pollAfterMs, remainingBeforeSleep), signal);
16989
- if (signal.aborted) throw signal.reason;
16990
- const remainingBeforeRequest = start.expiresAt - now();
16991
- if (remainingBeforeRequest <= 0) return expiredStatus(start);
16992
- let raw;
16993
- try {
16994
- raw = await client.get(path, {
16995
- signal: AbortSignal.any([
16996
- signal,
16997
- AbortSignal.timeout(Math.min(POLL_REQUEST_TIMEOUT_MS, remainingBeforeRequest))
16998
- ])
16999
- });
17000
- } catch (error) {
17001
- if (signal.aborted) throw error;
17002
- if (now() >= start.expiresAt) return expiredStatus(start);
17003
- throw error;
17004
- }
17005
- const status = parseGitHubInstallIntentStatus(raw, start.expiresAt);
17006
- if (!status) throw new Error("server returned an invalid GitHub install-intent status");
17007
- if (status.status !== "pending" && status.status !== "claimed") return status;
17008
- }
17009
- }
17010
-
17011
- // src/commands/github.ts
17012
- var BIND_TIMEOUT_MS = 1e4;
17013
- var START_TIMEOUT_MS = 1e4;
17014
- var EXIT_OK3 = 0;
17015
- var EXIT_FAILURE2 = 1;
17016
- var EXIT_UNBOUND = 2;
17017
- var defaultDependencies3 = {
17018
- cwd: () => process.cwd(),
17019
- gitToplevel,
17020
- bindRepositoryWithClient,
17021
- getPinnedClient,
17022
- createInstallIntent: createGitHubInstallIntent,
17023
- pollInstallIntent: pollGitHubInstallIntent,
17024
- openBrowser,
17025
- now: Date.now
17026
- };
17027
- function errorMessage(error) {
17028
- return error instanceof Error ? error.message : String(error);
17029
- }
17030
- function reportConnectFailure(error) {
17031
- const message = errorMessage(error);
17032
- const human = boundedHealthError(message) ?? "unknown error";
17033
- process.stderr.write(`[prim] github connect failed: ${human}
17034
- `);
17035
- printJson({
17036
- status: "error",
17037
- error: message,
17038
- ...error instanceof HttpError ? { httpStatus: error.status } : {}
17039
- });
17040
- process.exitCode = EXIT_FAILURE2;
17041
- }
17042
- function reportBinding(binding, installAttempted = false) {
17043
- if (binding.status === "connected") {
17044
- process.stderr.write(
17045
- `[prim] repository binding connected for GitHub origin ${binding.repositoryFullName}
17046
- `
17047
- );
17048
- printJson(binding);
17049
- process.exitCode = EXIT_OK3;
17050
- return;
17051
- }
17052
- process.stderr.write(
17053
- installAttempted ? `[prim] GitHub installation completed, but ${binding.repositoryFullName} was not granted admin access; repository binding remains unbound
17054
- ` : `[prim] repository binding unbound for GitHub origin ${binding.repositoryFullName}; starting GitHub App installation
17055
- `
17056
- );
17057
- printJson(binding);
17058
- process.exitCode = EXIT_UNBOUND;
17059
- }
17060
- function terminalInstallError(status) {
17061
- if (status.status === "failed_terminal") {
17062
- return new Error(`GitHub installation failed: ${status.failureCode}`);
17063
- }
17064
- return new Error(`GitHub installation ${status.status}`);
17065
- }
17066
- async function completeInstallIntent(client, start, dependencies, browser) {
17067
- process.stderr.write(`[prim] complete GitHub App installation at:
17068
- ${start.browserUrl}
17069
- `);
17070
- if (browser) dependencies.openBrowser(start.browserUrl);
17071
- return dependencies.pollInstallIntent(client, start, {
17072
- now: dependencies.now
17073
- });
17074
- }
17075
- async function performGithubConnect(dependencies = defaultDependencies3, options = {}) {
17076
- const root = dependencies.gitToplevel(dependencies.cwd());
17077
- if (!root) {
17078
- reportConnectFailure(
17079
- new Error("not a git repository \u2014 run `prim github connect` inside a GitHub repository")
17080
- );
17081
- return;
17082
- }
17083
- try {
17084
- const client = await dependencies.getPinnedClient({
17085
- signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
17086
- });
17087
- const existing = await dependencies.bindRepositoryWithClient(root, client, {
17088
- signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
17089
- });
17090
- if (existing.status === "connected") {
17091
- reportBinding(existing);
17092
- return;
17093
- }
17094
- const start = await dependencies.createInstallIntent(client, {
17095
- signal: AbortSignal.timeout(START_TIMEOUT_MS),
17096
- now: dependencies.now
17097
- });
17098
- const status = await completeInstallIntent(
17099
- client,
17100
- start,
17101
- dependencies,
17102
- options.browser ?? true
17103
- );
17104
- if (status.status !== "consumed") throw terminalInstallError(status);
17105
- process.stderr.write(
17106
- `[prim] GitHub installation verified: ${status.adminRepositoryCount} admin repositories (${status.repositoryCount} total)
17107
- `
17108
- );
17109
- const binding = await dependencies.bindRepositoryWithClient(root, client, {
17110
- signal: AbortSignal.timeout(BIND_TIMEOUT_MS)
17111
- });
17112
- reportBinding(binding, true);
17113
- } catch (error) {
17114
- reportConnectFailure(error);
17115
- }
17116
- }
17117
- function registerGithubCommands(program2, dependencies = defaultDependencies3) {
17118
- const github = program2.command("github").description("Manage GitHub repository bindings");
17119
- github.command("connect").description("Install or reuse the Primitive GitHub App and bind the current GitHub origin").option("--no-browser", "Print the GitHub installation URL without opening a browser").action(async (options, command) => {
17120
- const globals = command.optsWithGlobals();
17121
- await performGithubConnect(dependencies, {
17122
- browser: options.browser && globals.nonInteractive !== true
17123
- });
17124
- });
17125
- }
17126
-
17127
17181
  // src/commands/hooks.ts
17128
17182
  import { execFileSync } from "child_process";
17129
17183
  import {
@@ -17442,14 +17496,9 @@ function writeOwnHooks() {
17442
17496
  mkdirSync4(PRIM_GIT_HOOKS_DIR, { recursive: true });
17443
17497
  }
17444
17498
  for (const spec of HOOKS) {
17445
- const path = resolve3(PRIM_GIT_HOOKS_DIR, spec.hookName);
17446
- if (spec.hookName === POST_COMMIT.hookName) {
17447
- ensurePostCommitHookAtPath(path, globalHookScript(spec));
17448
- } else if (spec.hookName === POST_REWRITE.hookName) {
17449
- writeFileSync3(path, globalHookScript(spec), { mode: 493 });
17450
- } else {
17451
- writeFileSync3(path, globalHookScript(spec), { mode: 493 });
17452
- }
17499
+ writeFileSync3(resolve3(PRIM_GIT_HOOKS_DIR, spec.hookName), globalHookScript(spec), {
17500
+ mode: 493
17501
+ });
17453
17502
  }
17454
17503
  for (const name of PASSTHROUGH_HOOKS) {
17455
17504
  writeFileSync3(resolve3(PRIM_GIT_HOOKS_DIR, name), passThroughScript(name), { mode: 493 });
@@ -18486,6 +18535,7 @@ function registerSetupCommand(program2, dependencies = {}) {
18486
18535
  const agent = agentInput;
18487
18536
  const scope = opts.scope;
18488
18537
  const self = process.argv[1];
18538
+ const globals = program2.optsWithGlobals();
18489
18539
  const run = dependencies.run ?? ((args, capture = false) => {
18490
18540
  const r = spawnSync2(process.execPath, [self, ...args], {
18491
18541
  stdio: capture ? ["inherit", "pipe", "ignore"] : "inherit",
@@ -18555,7 +18605,12 @@ function registerSetupCommand(program2, dependencies = {}) {
18555
18605
  const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
18556
18606
  if (enableStep) {
18557
18607
  note(`${enableStep.label} \xB7 installing\u2026`);
18558
- const { code } = run(enableStep.args);
18608
+ const enableArgs = [
18609
+ ...enableStep.args,
18610
+ ...globals.yes ? ["--yes"] : [],
18611
+ ...globals.nonInteractive ? ["--non-interactive"] : []
18612
+ ];
18613
+ const { code } = run(enableArgs);
18559
18614
  results[enableStep.key] = code === 0 ? "ok" : enableStep.required ? "failed" : "skipped";
18560
18615
  }
18561
18616
  const healthStep = setupSteps.find((candidate) => candidate.key === "health");