@primitive.ai/prim 0.1.0-alpha.125 → 0.1.0-alpha.127

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.
Files changed (45) hide show
  1. package/README.md +140 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
  4. package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
  5. package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
  6. package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
  7. package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
  8. package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
  9. package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
  10. package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
  11. package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
  12. package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
  13. package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
  14. package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
  15. package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
  16. package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
  17. package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
  18. package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
  19. package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
  20. package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
  21. package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
  22. package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
  23. package/dist/daemon/server.js +805 -218
  24. package/dist/hook-runtime/daemon/server.js +805 -218
  25. package/dist/hook-runtime/hooks/post-commit.js +286 -59
  26. package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
  27. package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
  28. package/dist/hook-runtime/hooks/pre-commit.js +536 -88
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
  30. package/dist/hook-runtime/hooks/prim-hook.js +642 -167
  31. package/dist/hook-runtime/hooks/session-end.js +263 -47
  32. package/dist/hook-runtime/hooks/session-start.js +1103 -476
  33. package/dist/hook-runtime/index.js +3645 -2120
  34. package/dist/hook-runtime/statusline-main.js +257 -29
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +15 -15
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +49 -18
  43. package/dist/index.js +1014 -271
  44. package/dist/statusline-main.js +257 -29
  45. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import {
3
3
  bindRepository,
4
4
  bindRepositoryWithClient,
5
+ cloudAllowedDomains,
6
+ cloudEgressRemedy,
5
7
  codexWelcomeSkillPath,
6
8
  ensureEffectiveGitHook,
7
9
  ensureGitHookAtPath,
@@ -9,6 +11,7 @@ import {
9
11
  gitHooksMode,
10
12
  hasCurrentHookBlock,
11
13
  inspectEffectiveGitHook,
14
+ isCloudMachineSession,
12
15
  isLegacyOwnedGlobalHook,
13
16
  isOwnedStandalonePreCommit,
14
17
  kickDaemonEnsure,
@@ -16,13 +19,14 @@ import {
16
19
  projectGitHookTarget,
17
20
  projectHooksDir,
18
21
  registerSkillCommands,
22
+ repositoryIdentityRemedy,
19
23
  resolveEffectiveGitHook,
20
24
  resolveRepositoryBinding,
21
25
  uninstallGitHookAtPath,
22
26
  uninstallProjectGitHook,
23
27
  userTargetFor,
24
28
  welcomeSkillPathFor
25
- } from "./chunk-JFWJN2ME.js";
29
+ } from "./chunk-72NIZMZN.js";
26
30
  import {
27
31
  InvalidJournalEnvelopeError,
28
32
  buildOrganizationBoundMoveRequest,
@@ -30,27 +34,27 @@ import {
30
34
  inspectJournalDelivery,
31
35
  requireDurableIngestAcknowledgement,
32
36
  summarizeRetainedBuckets
33
- } from "./chunk-TI37ME2D.js";
37
+ } from "./chunk-L6IL4N6Y.js";
34
38
  import {
35
39
  checkAffectedDecisions,
36
40
  daemonOrDirectGet,
37
41
  formatDecisionsWarning
38
- } from "./chunk-EZXIKEMA.js";
42
+ } from "./chunk-VVFVENU4.js";
39
43
  import {
40
44
  hasCompleteCoverage,
41
45
  requestPreflight2 as requestPreflight,
42
46
  waitForPreflight
43
- } from "./chunk-6OPSSJHO.js";
47
+ } from "./chunk-C4QNBSWB.js";
44
48
  import {
45
49
  fetchFeedbackCapability
46
- } from "./chunk-PPZ56EVJ.js";
50
+ } from "./chunk-TNWI3JWK.js";
47
51
  import {
48
52
  POST_COMMIT_GRACE_MS,
49
53
  clearHooksWired,
50
54
  inspectPostCommitFiring,
51
55
  lastConversationCaptured,
52
56
  recordHooksWired
53
- } from "./chunk-BFYJLI7V.js";
57
+ } from "./chunk-F3FDVHR7.js";
54
58
  import {
55
59
  isUnattended,
56
60
  unattendedEnv
@@ -63,7 +67,7 @@ import {
63
67
  formatStatusline,
64
68
  formatTeammates,
65
69
  repositoryBindingDiagnosticLabel
66
- } from "./chunk-6KXQQ7CQ.js";
70
+ } from "./chunk-URYZDQFH.js";
67
71
  import {
68
72
  JOURNAL_DIR,
69
73
  SESSIONS_DIR,
@@ -78,11 +82,11 @@ import {
78
82
  rotationIdentity,
79
83
  sweepOrphanedDrainProgress,
80
84
  writeDrainCheckpoint
81
- } from "./chunk-NBNQI3YJ.js";
85
+ } from "./chunk-O65UVJZH.js";
82
86
  import {
83
87
  daemonIsLive,
84
88
  daemonRequest
85
- } from "./chunk-YP4OXKNX.js";
89
+ } from "./chunk-H6X52UVF.js";
86
90
  import {
87
91
  RUN_ID,
88
92
  demoCommand,
@@ -103,13 +107,15 @@ import {
103
107
  readRun,
104
108
  runIds,
105
109
  saveRun
106
- } from "./chunk-HPA7RGSZ.js";
110
+ } from "./chunk-MGKSZSTV.js";
107
111
  import {
108
112
  MANAGED_GIT_HOOK_NAMES,
109
113
  assertOwnedHookRuntime,
110
114
  atomicWrite,
115
+ cloudUserInstallComplete,
111
116
  ensureRegistration,
112
117
  entryHasCommand,
118
+ hasDeveloperUserInstall,
113
119
  hookRuntimePaths,
114
120
  inspectFailureProtection,
115
121
  inspectGitHookEntrypoint,
@@ -118,8 +124,10 @@ import {
118
124
  inspectHookRuntimeResolutions2,
119
125
  makeRegistration,
120
126
  managedHookBlock,
127
+ performCloudUserInstall,
121
128
  performStatus,
122
129
  performStatus2,
130
+ planProjectInactiveDeclaration,
123
131
  projectRoot,
124
132
  readSettings,
125
133
  registerClaudeCommands,
@@ -129,9 +137,10 @@ import {
129
137
  stableNodePath,
130
138
  stageHookRuntime,
131
139
  stripCommand
132
- } from "./chunk-L32WYFJT.js";
133
- import "./chunk-74DQDWLW.js";
140
+ } from "./chunk-UUQT5GMO.js";
141
+ import "./chunk-R4EYLEIK.js";
134
142
  import {
143
+ MAX_SCOPE_GLOB_CHARS,
135
144
  bold,
136
145
  boundedHealthError,
137
146
  color,
@@ -155,14 +164,18 @@ import {
155
164
  isGitHubInstallIntentStartResponse,
156
165
  isGitHubInstallIntentStatusResponse,
157
166
  isReconcileResolutionResponse,
167
+ isScopeDirectoryPrefix,
168
+ isScopeGlobPattern,
158
169
  stripAnsi
159
- } from "./chunk-O73J3KQQ.js";
170
+ } from "./chunk-WGTUNUIS.js";
160
171
  import {
161
172
  CliManagementResponseError,
173
+ DEFAULT_API_URL,
162
174
  HttpError,
163
175
  clearStoredCredentials,
164
176
  commitCredentials,
165
177
  decisionIdentifier,
178
+ getBearerClient,
166
179
  getClient,
167
180
  getPinnedClient,
168
181
  getPinnedManagementClient,
@@ -174,10 +187,14 @@ import {
174
187
  setStoredToken,
175
188
  stripControlChars,
176
189
  terminalSafeLine
177
- } from "./chunk-ZKXNJB6U.js";
190
+ } from "./chunk-NVDPKW7Z.js";
178
191
  import {
192
+ CLOUD_CREDENTIALS_REMEDY,
193
+ CLOUD_GITHUB_CONNECT_REMEDY,
194
+ CLOUD_SETUP_POINTER,
179
195
  MachineAuthError,
180
196
  REFRESH_TOKEN_PATH,
197
+ SERVER_WAIT_PREFIX,
181
198
  TOKEN_FILE_PATH,
182
199
  WorkosConnectProtocolError,
183
200
  acquireMachineCredential,
@@ -185,33 +202,48 @@ import {
185
202
  binFile,
186
203
  canonicalGitRoot,
187
204
  canonicalRepositoryPath,
205
+ clearCloudPrepared,
188
206
  clearDemoPause,
207
+ clearMachineCooldowns,
189
208
  clearMachineCredentials,
190
209
  commandMatchesBin,
191
210
  compareSemver,
192
211
  configureMachine,
193
212
  decisionIngestionStatus,
213
+ declaresInactive,
194
214
  discoverMachineConfiguration,
195
215
  discoverWorkosConnect,
196
216
  endDemoPause,
197
217
  environmentCredentials,
218
+ exchangeMachineCredentials,
219
+ explicitlyActive,
198
220
  extendDemoPause,
199
221
  gitToplevel,
222
+ githubRepositoryFullName,
200
223
  hasMachineConfiguration,
224
+ hasProjectPrimInstall,
201
225
  healDemoPause,
202
226
  hookCommandResolutions,
227
+ insideClaudeCode,
228
+ isClaudeCloudSession,
229
+ isGitIgnored,
230
+ isPreparedCloudSession,
203
231
  isRepoActiveForCapture,
204
232
  isValidRepoSyncId,
233
+ machineApiUrl,
205
234
  machineContext,
206
235
  machineRecord,
207
236
  machineString,
208
237
  mainWorktreeRoot,
238
+ markActivationExplicit,
239
+ markCloudPrepared,
209
240
  packageRoot,
210
241
  packageVersion,
211
242
  pauseCaptureForDemo,
212
243
  pinnedNpxArgs,
213
244
  pollWorkosDeviceAuthorization,
214
245
  prepareMachineMetadataDirectory,
246
+ preparedInSession,
215
247
  primConfigDirectory,
216
248
  processIsAlive,
217
249
  readDemoPause,
@@ -221,14 +253,16 @@ import {
221
253
  repositoryBindingState,
222
254
  requestWorkosDeviceAuthorization,
223
255
  resolveAuthCredential,
256
+ resolveStoredCredential,
224
257
  setRepoActive,
225
258
  stableHookCommand,
226
259
  syncDirectory,
260
+ verifyAcquiredMachineIdentity,
227
261
  verifyMachineIdentity,
228
262
  withFileLock,
229
263
  withFileLockSync,
230
264
  writeMachineMetadata
231
- } from "./chunk-NJBN3WXF.js";
265
+ } from "./chunk-HZI5PBN4.js";
232
266
  import "./chunk-JSBRDJBE.js";
233
267
 
234
268
  // src/index.ts
@@ -912,6 +946,160 @@ async function activatePending(identity) {
912
946
  return true;
913
947
  }
914
948
  }
949
+ async function exchangeEnrollment(client, request, onStarted) {
950
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
951
+ const verifier = randomBytes2(32).toString("hex");
952
+ const signal = AbortSignal.timeout(6e4);
953
+ const start = machineRecord(
954
+ await client.post(
955
+ "/api/cli/auth/enrollment/start",
956
+ {
957
+ installationId: request.installationId,
958
+ requestId: randomUUID(),
959
+ displayName: request.displayName,
960
+ publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
961
+ challenge: createHash2("sha256").update(verifier).digest("hex")
962
+ },
963
+ { signal }
964
+ )
965
+ );
966
+ if (!isCliEnrollmentStartResponse(start) || !machineString(start.enrollmentId, 128))
967
+ throw new MachineAuthError("invalid_enrollment", "The server returned an invalid enrollment.");
968
+ onStarted?.();
969
+ const response = machineRecord(
970
+ await client.post(
971
+ "/api/cli/auth/enrollment/redeem",
972
+ { enrollmentId: start.enrollmentId, verifier },
973
+ { signal }
974
+ )
975
+ );
976
+ if (!isCliEnrollmentRedeemResponse(response) || !machineString(response.clientId, 256) || !machineString(response.ciphertext, 4096) || !machineString(response.machineId, 128) || response.authorizedUserId !== request.authorizedUserId)
977
+ throw new MachineAuthError(
978
+ "invalid_enrollment",
979
+ "The server returned an invalid enrollment exchange."
980
+ );
981
+ try {
982
+ return {
983
+ enrollmentId: start.enrollmentId,
984
+ clientId: response.clientId,
985
+ machineId: response.machineId,
986
+ secret: privateDecrypt(
987
+ { key: privateKey, padding: constants2.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
988
+ Buffer.from(response.ciphertext, "base64")
989
+ ).toString("utf8")
990
+ };
991
+ } catch {
992
+ throw new MachineAuthError(
993
+ "invalid_enrollment",
994
+ "The credential exchange could not be decrypted for this installation."
995
+ );
996
+ }
997
+ }
998
+ async function enrollmentOwner(client, rejectedSessionHint = "Sign in once with prim auth login to authorize this developer installation.") {
999
+ let status2;
1000
+ try {
1001
+ status2 = machineRecord(
1002
+ await client.get("/api/cli/auth/enrollment/status", {
1003
+ signal: AbortSignal.timeout(15e3)
1004
+ })
1005
+ );
1006
+ } catch (error) {
1007
+ if (error instanceof HttpError && (error.status === 401 || error.status === 403))
1008
+ throw new MachineAuthError("human_sign_in_required", rejectedSessionHint);
1009
+ throw error;
1010
+ }
1011
+ if (!machineString(status2.userId, 128) || !machineString(status2.organizationId, 128))
1012
+ throw new MachineAuthError(
1013
+ "invalid_enrollment",
1014
+ "The server did not verify the enrollment user and organization."
1015
+ );
1016
+ return { authorizedUserId: status2.userId, organizationId: status2.organizationId };
1017
+ }
1018
+ var INSTALLATION_NAME_MAX_LENGTH = 128;
1019
+ var ENV_VALUE = /^[\w.~+/:=-]+$/u;
1020
+ async function prepareEnvironmentEnrollment(displayName) {
1021
+ const name = displayName.trim();
1022
+ if (!machineString(name, INSTALLATION_NAME_MAX_LENGTH))
1023
+ throw new MachineAuthError(
1024
+ "invalid_installation_name",
1025
+ `Name the installation with 1-${INSTALLATION_NAME_MAX_LENGTH} printable characters.`
1026
+ );
1027
+ let siteUrl;
1028
+ try {
1029
+ siteUrl = machineApiUrl(getSiteUrl());
1030
+ } catch {
1031
+ siteUrl = "";
1032
+ }
1033
+ if (!siteUrl || !ENV_VALUE.test(siteUrl))
1034
+ throw new MachineAuthError(
1035
+ "invalid_configuration",
1036
+ "PRIM_API_URL must be an HTTPS origin that can be written as an .env value."
1037
+ );
1038
+ const configuration = await discoverMachineConfiguration(siteUrl);
1039
+ if (!configuration.developerEnrollment)
1040
+ throw new MachineAuthError(
1041
+ "enrollment_unavailable",
1042
+ "Automatic enrollment is not enabled on this server."
1043
+ );
1044
+ return { name, siteUrl, configuration };
1045
+ }
1046
+ async function enrollEnvironmentInstallation({ name, siteUrl, configuration }, humanAccessToken) {
1047
+ const client = getBearerClient(humanAccessToken, siteUrl);
1048
+ const owner = await enrollmentOwner(
1049
+ client,
1050
+ "The server did not accept this sign-in for enrollment. Check the organization's enrollment policy, then retry."
1051
+ );
1052
+ let registered = false;
1053
+ try {
1054
+ const { clientId, machineId, secret } = await exchangeEnrollment(
1055
+ client,
1056
+ { installationId: randomUUID(), displayName: name, authorizedUserId: owner.authorizedUserId },
1057
+ () => {
1058
+ registered = true;
1059
+ }
1060
+ );
1061
+ const tokens = await exchangeMachineCredentials(configuration, clientId, secret);
1062
+ const identity = await verifyMachineIdentity(siteUrl, tokens.accessToken, clientId);
1063
+ if (identity.machineId !== machineId || identity.authorizedUserId !== owner.authorizedUserId || identity.organizationId !== owner.organizationId)
1064
+ throw new MachineAuthError(
1065
+ "delegation_mismatch",
1066
+ "The new installation does not carry the signed-in user's delegation.",
1067
+ true
1068
+ );
1069
+ return {
1070
+ environment: installationEnvironment({ clientId, clientSecret: secret }, siteUrl),
1071
+ displayName: name,
1072
+ clientId,
1073
+ clientSecret: secret,
1074
+ machineId,
1075
+ authorizedUserId: owner.authorizedUserId,
1076
+ organizationId: owner.organizationId
1077
+ };
1078
+ } catch (error) {
1079
+ const uncertain = !registered && !(error instanceof HttpError && error.status < 500);
1080
+ if (!registered && !uncertain) throw error;
1081
+ const cause = error instanceof MachineAuthError ? error.message : "Enrollment could not finish.";
1082
+ throw new MachineAuthError(
1083
+ error instanceof MachineAuthError ? error.code : "enrollment_failed",
1084
+ `${cause} Installation "${name}" ${registered ? "was already registered" : "may have been registered"}; ask an organization admin to revoke it in Settings \u2192 Developer installations.`
1085
+ );
1086
+ }
1087
+ }
1088
+ function installationEnvironment(installation, siteUrl) {
1089
+ const entries = [
1090
+ ["PRIM_M2M_CLIENT_ID", installation.clientId],
1091
+ ["PRIM_M2M_CLIENT_SECRET", installation.clientSecret]
1092
+ ];
1093
+ if (siteUrl !== DEFAULT_API_URL) entries.push(["PRIM_API_URL", siteUrl]);
1094
+ return entries.map(([key, value]) => {
1095
+ if (!ENV_VALUE.test(value))
1096
+ throw new MachineAuthError(
1097
+ "invalid_credentials",
1098
+ `${key} cannot be written as an .env value.`
1099
+ );
1100
+ return `${key}=${value}`;
1101
+ });
1102
+ }
915
1103
  async function enrollDeveloperInstallation(ifSupported = false) {
916
1104
  if (hasMachineConfiguration()) {
917
1105
  const current = await acquireMachineCredential();
@@ -959,27 +1147,7 @@ async function enrollDeveloperInstallation(ifSupported = false) {
959
1147
  };
960
1148
  }
961
1149
  const client = await getPinnedClient();
962
- let status2;
963
- try {
964
- status2 = machineRecord(
965
- await client.get("/api/cli/auth/enrollment/status", {
966
- signal: AbortSignal.timeout(15e3)
967
- })
968
- );
969
- } catch (error) {
970
- if (error instanceof HttpError && (error.status === 401 || error.status === 403))
971
- throw new MachineAuthError(
972
- "human_sign_in_required",
973
- "Sign in once with prim auth login to authorize this developer installation."
974
- );
975
- throw error;
976
- }
977
- if (!machineString(status2.userId, 128) || !machineString(status2.organizationId, 128))
978
- throw new MachineAuthError(
979
- "invalid_enrollment",
980
- "The server did not verify the enrollment user and organization."
981
- );
982
- const owner = { authorizedUserId: status2.userId, organizationId: status2.organizationId };
1150
+ const owner = await enrollmentOwner(client);
983
1151
  const path = installationPath(owner, directory);
984
1152
  let installationId;
985
1153
  try {
@@ -1000,58 +1168,18 @@ async function enrollDeveloperInstallation(ifSupported = false) {
1000
1168
  await flush();
1001
1169
  } catch {
1002
1170
  }
1003
- const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
1004
- const verifier = randomBytes2(32).toString("hex");
1005
- const signal = AbortSignal.timeout(6e4);
1006
- const start = machineRecord(
1007
- await client.post(
1008
- "/api/cli/auth/enrollment/start",
1009
- {
1010
- installationId,
1011
- requestId: randomUUID(),
1012
- displayName: hostname().slice(0, 128),
1013
- publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
1014
- challenge: createHash2("sha256").update(verifier).digest("hex")
1015
- },
1016
- { signal }
1017
- )
1018
- );
1019
- if (!isCliEnrollmentStartResponse(start) || !machineString(start.enrollmentId, 128))
1020
- throw new MachineAuthError(
1021
- "invalid_enrollment",
1022
- "The server returned an invalid enrollment."
1023
- );
1024
- const response = machineRecord(
1025
- await client.post(
1026
- "/api/cli/auth/enrollment/redeem",
1027
- { enrollmentId: start.enrollmentId, verifier },
1028
- { signal }
1029
- )
1030
- );
1031
- if (!isCliEnrollmentRedeemResponse(response) || !machineString(response.clientId, 256) || !machineString(response.ciphertext, 4096) || response.authorizedUserId !== owner.authorizedUserId)
1032
- throw new MachineAuthError(
1033
- "invalid_enrollment",
1034
- "The server returned an invalid enrollment exchange."
1035
- );
1036
- let secret;
1037
- try {
1038
- secret = privateDecrypt(
1039
- { key: privateKey, padding: constants2.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
1040
- Buffer.from(response.ciphertext, "base64")
1041
- ).toString("utf8");
1042
- } catch {
1043
- throw new MachineAuthError(
1044
- "invalid_enrollment",
1045
- "The credential exchange could not be decrypted for this installation."
1046
- );
1047
- }
1048
- const profile = await configureMachine(response.clientId, secret, {
1171
+ const { enrollmentId, clientId, secret } = await exchangeEnrollment(client, {
1172
+ installationId,
1173
+ displayName: hostname().slice(0, 128),
1174
+ authorizedUserId: owner.authorizedUserId
1175
+ });
1176
+ const profile = await configureMachine(clientId, secret, {
1049
1177
  expectedAuthorizedUserId: owner.authorizedUserId,
1050
1178
  expectedOrganizationId: owner.organizationId
1051
1179
  });
1052
1180
  writeMachineMetadata(path, {
1053
1181
  installationId,
1054
- pendingEnrollmentId: start.enrollmentId,
1182
+ pendingEnrollmentId: enrollmentId,
1055
1183
  pendingMachineId: profile.machineId
1056
1184
  });
1057
1185
  const activationPending = await activatePending(profile);
@@ -1674,16 +1802,12 @@ async function verifyAuthStatus() {
1674
1802
  signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS)
1675
1803
  });
1676
1804
  if (!machine) throw new Error("missing machine");
1677
- machineMetadata = {
1678
- ...machineMetadata,
1805
+ const tokenExpiry = machine.tokenInjection ? { accessTokenExpiresInMs: null, accessTokenExpired: false, tokenHeldByProxy: true } : {
1679
1806
  accessTokenExpiresInMs: machine.expiresAt - Date.now(),
1680
1807
  accessTokenExpired: machine.expiresAt <= Date.now()
1681
1808
  };
1682
- const identity = await verifyMachineIdentity(
1683
- machine.apiUrl,
1684
- machine.accessToken,
1685
- machine.clientId
1686
- );
1809
+ machineMetadata = { ...machineMetadata, ...tokenExpiry };
1810
+ const identity = await verifyAcquiredMachineIdentity(machine);
1687
1811
  return {
1688
1812
  ...authStatusResult("valid", "verified", "machine", false),
1689
1813
  principalKind: "machine",
@@ -1693,8 +1817,7 @@ async function verifyAuthStatus() {
1693
1817
  effectiveScopes: identity.scopes,
1694
1818
  organizationId: machine.organizationId,
1695
1819
  storageBackend: machine.storage,
1696
- accessTokenExpiresInMs: machine.expiresAt - Date.now(),
1697
- accessTokenExpired: machine.expiresAt <= Date.now()
1820
+ ...tokenExpiry
1698
1821
  };
1699
1822
  }
1700
1823
  } catch (error) {
@@ -1713,7 +1836,8 @@ async function verifyAuthStatus() {
1713
1836
  ),
1714
1837
  ...machineMetadata,
1715
1838
  principalKind: "machine",
1716
- recoveryReason: error instanceof MachineAuthError ? error.code : "verification_unavailable"
1839
+ recoveryReason: error instanceof MachineAuthError ? error.code : "verification_unavailable",
1840
+ ...error instanceof MachineAuthError ? { recoveryDetail: error.message } : {}
1717
1841
  };
1718
1842
  }
1719
1843
  const credential = resolveAuthCredential();
@@ -1799,13 +1923,15 @@ function authStatusExitCode(status2) {
1799
1923
  function writeHumanAuthStatus(result) {
1800
1924
  if (result.principalKind === "machine") {
1801
1925
  console.error(
1802
- result.authenticated ? `Installation ${result.machineId}: verified (${result.storageBackend}); organization ${result.organizationId}${result.authorizedUserId ? `; acting for user ${result.authorizedUserId}` : "; service identity"}.` : `Machine authentication ${result.status}: ${result.recoveryReason}. Check the credential store or run prim auth configure-machine with credentials from your administrator.`
1926
+ result.authenticated ? `Installation ${result.machineId}: verified (${result.storageBackend}); organization ${result.organizationId}${result.authorizedUserId ? `; acting for user ${result.authorizedUserId}` : "; service identity"}.` : `Machine authentication ${result.status}: ${result.recoveryReason}. ${result.recoveryDetail ? stripControlChars(result.recoveryDetail) : "Check the credential store or run prim auth configure-machine with credentials from your administrator."}`
1803
1927
  );
1804
1928
  return;
1805
1929
  }
1806
1930
  if (result.status === "invalid") {
1807
1931
  const detail = result.reason === "refresh_rejected" ? "The saved session was rejected." : result.reason === "access_rejected" ? "The selected access token was rejected." : "No credentials were found.";
1808
- console.log(`${detail} Run \`prim auth login\` to authenticate.`);
1932
+ console.log(
1933
+ isClaudeCloudSession() ? `${detail} In a Claude Code cloud session, ${CLOUD_CREDENTIALS_REMEDY}.` : `${detail} Run \`prim auth login\` to authenticate.`
1934
+ );
1809
1935
  return;
1810
1936
  }
1811
1937
  if (result.status === "unreachable") {
@@ -1842,10 +1968,218 @@ function requiresLegacyAuthentication() {
1842
1968
  );
1843
1969
  return false;
1844
1970
  }
1971
+ async function signInInteractively(options) {
1972
+ const siteUrl = getSiteUrl();
1973
+ let discovery;
1974
+ try {
1975
+ discovery = await discoverWorkosConnect(siteUrl);
1976
+ } catch (error) {
1977
+ return {
1978
+ ok: false,
1979
+ error: error instanceof WorkosConnectProtocolError ? error.code : "config_fetch_failed",
1980
+ detail: error instanceof Error ? error.message : "Connect discovery failed"
1981
+ };
1982
+ }
1983
+ if (discovery.state === "available") {
1984
+ try {
1985
+ const authorization = await requestWorkosDeviceAuthorization(discovery.configuration);
1986
+ const verificationUrl = authorization.verificationUriComplete ?? authorization.verificationUri;
1987
+ console.error(`Authenticate at:
1988
+ ${verificationUrl}`);
1989
+ console.error(`Verification code: ${authorization.userCode}`);
1990
+ if (options.browser) openBrowser(verificationUrl);
1991
+ const tokens = await pollWorkosDeviceAuthorization(discovery.configuration, authorization);
1992
+ return {
1993
+ ok: true,
1994
+ flow: "device",
1995
+ credentials: {
1996
+ ...tokens,
1997
+ metadata: {
1998
+ version: 1,
1999
+ family: "workos_connect",
2000
+ issuer: discovery.configuration.issuer,
2001
+ clientId: discovery.configuration.clientId
2002
+ }
2003
+ }
2004
+ };
2005
+ } catch (error) {
2006
+ return {
2007
+ ok: false,
2008
+ error: error instanceof WorkosConnectProtocolError ? error.code : "device_authorization_failed",
2009
+ detail: error instanceof Error ? error.message : "Device authorization failed"
2010
+ };
2011
+ }
2012
+ }
2013
+ let config;
2014
+ try {
2015
+ config = await fetchAuthBrokerConfig(siteUrl);
2016
+ } catch {
2017
+ return {
2018
+ ok: false,
2019
+ error: "config_fetch_failed",
2020
+ detail: "Failed to fetch MCP config. Is the Convex backend running?"
2021
+ };
2022
+ }
2023
+ const { verifier, challenge } = generatePkce();
2024
+ const state = base64url(randomBytes4(16));
2025
+ const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
2026
+ let settle;
2027
+ const outcome = new Promise((resolve8) => {
2028
+ settle = resolve8;
2029
+ });
2030
+ const server = createServer((req, res) => {
2031
+ const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
2032
+ if (url.pathname !== "/callback") {
2033
+ res.writeHead(404);
2034
+ res.end("Not found");
2035
+ return;
2036
+ }
2037
+ const page = resolveCallbackPage(url.searchParams, state);
2038
+ res.writeHead(page.status, HTML_HEADERS);
2039
+ res.end(page.html, () => settle(page.result));
2040
+ });
2041
+ try {
2042
+ await new Promise((resolve8, reject) => {
2043
+ const onError = (err) => reject(err);
2044
+ server.once("error", onError);
2045
+ server.listen(CALLBACK_PORT, LOCALHOST, () => {
2046
+ server.removeListener("error", onError);
2047
+ resolve8();
2048
+ });
2049
+ });
2050
+ } catch (err) {
2051
+ if (err instanceof Error && err.code === "EADDRINUSE") {
2052
+ return {
2053
+ ok: false,
2054
+ error: "callback_port_in_use",
2055
+ detail: `Port ${CALLBACK_PORT} is in use \u2014 another prim sign-in may be running. Close it and retry.`
2056
+ };
2057
+ }
2058
+ return {
2059
+ ok: false,
2060
+ error: "callback_bind_failed",
2061
+ detail: `Could not start the local callback server: ${err instanceof Error ? err.message : String(err)}`
2062
+ };
2063
+ }
2064
+ server.on("error", () => {
2065
+ });
2066
+ const authUrl = new URL(config.authorization_endpoint);
2067
+ authUrl.searchParams.set("client_id", config.client_id);
2068
+ authUrl.searchParams.set("redirect_uri", redirectUri);
2069
+ authUrl.searchParams.set("response_type", "code");
2070
+ authUrl.searchParams.set("provider", "authkit");
2071
+ authUrl.searchParams.set("scope", config.default_scopes.join(" "));
2072
+ authUrl.searchParams.set("state", state);
2073
+ authUrl.searchParams.set("code_challenge", challenge);
2074
+ authUrl.searchParams.set("code_challenge_method", "S256");
2075
+ if (options.browser) {
2076
+ console.error("Opening browser for authentication...");
2077
+ openBrowser(authUrl.toString());
2078
+ }
2079
+ console.error(`If the browser doesn't open, visit:
2080
+ ${authUrl.toString()}
2081
+ `);
2082
+ console.error("Waiting for callback...");
2083
+ const timer = setTimeout(() => {
2084
+ settle({ authenticated: false, error: "timeout", detail: "Authentication timed out." });
2085
+ }, CALLBACK_TIMEOUT_MS);
2086
+ timer.unref();
2087
+ const result = await outcome;
2088
+ clearTimeout(timer);
2089
+ server.close();
2090
+ if (!result.authenticated) {
2091
+ return { ok: false, error: result.error, detail: result.detail };
2092
+ }
2093
+ try {
2094
+ const tokens = await exchangeCode(siteUrl, result.code, verifier, redirectUri);
2095
+ return { ok: true, flow: "legacy", credentials: tokens };
2096
+ } catch (err) {
2097
+ return {
2098
+ ok: false,
2099
+ error: "token_exchange_failed",
2100
+ detail: err instanceof Error ? err.message : String(err)
2101
+ };
2102
+ }
2103
+ }
2104
+ function signInHost(issuer) {
2105
+ try {
2106
+ return new URL(issuer).hostname;
2107
+ } catch {
2108
+ return "the sign-in host";
2109
+ }
2110
+ }
2111
+ function reportEnrollmentFailure(error, detail) {
2112
+ const human = detail ? `${stripControlChars(error)}: ${stripControlChars(detail)}` : stripControlChars(error);
2113
+ console.error(`Enrollment failed: ${human}`);
2114
+ process.exitCode = EXIT_FAIL;
2115
+ }
2116
+ async function enrollNewInstallation(options) {
2117
+ if (!options.newInstallation || !options.printEnv || options.ifSupported) {
2118
+ reportEnrollmentFailure(
2119
+ "invalid_arguments",
2120
+ "Use --new-installation <name> together with --print-env (and without --if-supported)."
2121
+ );
2122
+ return;
2123
+ }
2124
+ try {
2125
+ const enrollment = await prepareEnvironmentEnrollment(options.newInstallation);
2126
+ console.error(
2127
+ `Sign in to authorize a new installation named "${stripControlChars(enrollment.name)}". This machine's own credentials are not changed.`
2128
+ );
2129
+ const signIn = await signInInteractively({ browser: options.browser });
2130
+ if (!signIn.ok) {
2131
+ reportEnrollmentFailure(signIn.error, signIn.detail);
2132
+ return;
2133
+ }
2134
+ const installation = await enrollEnvironmentInstallation(
2135
+ enrollment,
2136
+ signIn.credentials.accessToken
2137
+ );
2138
+ process.stdout.write(`${installation.environment.join("\n")}
2139
+ `);
2140
+ console.error(
2141
+ [
2142
+ `Installation "${stripControlChars(installation.displayName)}" is authorized for your account; its Decisions belong to you.`,
2143
+ "The secret is shown only once and is not stored on this machine.",
2144
+ // Anyone who uses a cloud environment can read its variables; its
2145
+ // network secrets cannot be read back, so say that way first.
2146
+ `For a Claude Code cloud environment, keep the secret out of the variables: add a "Username and password" network secret for ${signInHost(enrollment.configuration.issuer)} (username: the client ID, password: the client secret). As its variables, set PRIM_M2M_CLIENT_AUTH=network-secret and every line printed above except PRIM_M2M_CLIENT_SECRET.`,
2147
+ "Or paste every line above into the environment's variables, where anyone who uses the environment can read them.",
2148
+ "An organization admin can revoke the installation in Settings \u2192 Developer installations."
2149
+ ].join("\n")
2150
+ );
2151
+ process.exitCode = EXIT_OK;
2152
+ } catch (error) {
2153
+ reportEnrollmentFailure(
2154
+ error instanceof MachineAuthError ? error.code : "enrollment_failed",
2155
+ error instanceof MachineAuthError ? error.message : "Enrollment could not finish. Check the organization's enrollment policy, then retry."
2156
+ );
2157
+ }
2158
+ }
2159
+ function refuseCloudSignIn(report = reportFailure) {
2160
+ if (!isClaudeCloudSession()) return false;
2161
+ report(
2162
+ "cloud_session_sign_in_unavailable",
2163
+ `Interactive sign-in is not used inside a Claude Code cloud session. ${CLOUD_CREDENTIALS_REMEDY.charAt(0).toUpperCase()}${CLOUD_CREDENTIALS_REMEDY.slice(1)}.`
2164
+ );
2165
+ return true;
2166
+ }
1845
2167
  function registerAuthCommands(program2) {
1846
2168
  const auth = program2.command("auth").description("Manage CLI authentication");
1847
- auth.command("enroll").description("Authorize this developer installation using your signed-in account").option("--if-supported", "Keep legacy authentication when server enrollment is unavailable").action(async (options) => {
2169
+ auth.command("enroll").description("Authorize this developer installation using your signed-in account").option("--if-supported", "Keep legacy authentication when server enrollment is unavailable").option(
2170
+ "--new-installation <name>",
2171
+ "Enroll a separate installation that runs elsewhere, such as a Claude Code cloud environment (requires --print-env)"
2172
+ ).option(
2173
+ "--print-env",
2174
+ "Print the new installation's PRIM_M2M_* credentials to STDOUT as .env lines for an environment"
2175
+ ).option("--no-browser", "Print the sign-in URL without opening a browser").action(async (options) => {
2176
+ if (options.newInstallation !== void 0 || options.printEnv) {
2177
+ if (refuseCloudSignIn(reportEnrollmentFailure)) return;
2178
+ await enrollNewInstallation(options);
2179
+ return;
2180
+ }
1848
2181
  try {
2182
+ if (isClaudeCloudSession() && !hasMachineConfiguration() && refuseCloudSignIn()) return;
1849
2183
  const result = await enrollDeveloperInstallation(options.ifSupported);
1850
2184
  if (result.enrolled)
1851
2185
  console.error(
@@ -1924,134 +2258,20 @@ function registerAuthCommands(program2) {
1924
2258
  });
1925
2259
  auth.command("login").description("Authenticate via browser (WorkOS OAuth)").option("--no-browser", "Print the verification URL without opening a browser").action(async (options) => {
1926
2260
  if (!requiresLegacyAuthentication()) return;
1927
- const siteUrl = getSiteUrl();
1928
- let discovery;
1929
- try {
1930
- discovery = await discoverWorkosConnect(siteUrl);
1931
- } catch (error) {
1932
- reportFailure(
1933
- error instanceof WorkosConnectProtocolError ? error.code : "config_fetch_failed",
1934
- error instanceof Error ? error.message : "Connect discovery failed"
1935
- );
1936
- return;
1937
- }
1938
- if (discovery.state === "available") {
1939
- try {
1940
- const authorization = await requestWorkosDeviceAuthorization(discovery.configuration);
1941
- const verificationUrl = authorization.verificationUriComplete ?? authorization.verificationUri;
1942
- console.error(`Authenticate at:
1943
- ${verificationUrl}`);
1944
- console.error(`Verification code: ${authorization.userCode}`);
1945
- if (options.browser) openBrowser(verificationUrl);
1946
- const tokens = await pollWorkosDeviceAuthorization(
1947
- discovery.configuration,
1948
- authorization
1949
- );
1950
- await commitCredentials({
1951
- ...tokens,
1952
- metadata: {
1953
- version: 1,
1954
- family: "workos_connect",
1955
- issuer: discovery.configuration.issuer,
1956
- clientId: discovery.configuration.clientId
1957
- }
1958
- });
1959
- reportSuccess();
1960
- } catch (error) {
1961
- reportFailure(
1962
- error instanceof WorkosConnectProtocolError ? error.code : "device_authorization_failed",
1963
- error instanceof Error ? error.message : "Device authorization failed"
1964
- );
1965
- }
2261
+ if (refuseCloudSignIn()) return;
2262
+ const signIn = await signInInteractively(options);
2263
+ if (!signIn.ok) {
2264
+ reportFailure(signIn.error, signIn.detail);
1966
2265
  return;
1967
2266
  }
1968
- let config;
1969
2267
  try {
1970
- config = await fetchAuthBrokerConfig(siteUrl);
1971
- } catch {
2268
+ await commitCredentials(signIn.credentials);
2269
+ reportSuccess();
2270
+ } catch (error) {
1972
2271
  reportFailure(
1973
- "config_fetch_failed",
1974
- "Failed to fetch MCP config. Is the Convex backend running?"
2272
+ signIn.flow === "device" ? "device_authorization_failed" : "token_exchange_failed",
2273
+ error instanceof Error ? error.message : signIn.flow === "device" ? "Device authorization failed" : String(error)
1975
2274
  );
1976
- return;
1977
- }
1978
- const { verifier, challenge } = generatePkce();
1979
- const state = base64url(randomBytes4(16));
1980
- const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
1981
- let settle;
1982
- const outcome = new Promise((resolve8) => {
1983
- settle = resolve8;
1984
- });
1985
- const server = createServer((req, res) => {
1986
- const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
1987
- if (url.pathname !== "/callback") {
1988
- res.writeHead(404);
1989
- res.end("Not found");
1990
- return;
1991
- }
1992
- const page = resolveCallbackPage(url.searchParams, state);
1993
- res.writeHead(page.status, HTML_HEADERS);
1994
- res.end(page.html, () => settle(page.result));
1995
- });
1996
- try {
1997
- await new Promise((resolve8, reject) => {
1998
- const onError = (err) => reject(err);
1999
- server.once("error", onError);
2000
- server.listen(CALLBACK_PORT, LOCALHOST, () => {
2001
- server.removeListener("error", onError);
2002
- resolve8();
2003
- });
2004
- });
2005
- } catch (err) {
2006
- if (err instanceof Error && err.code === "EADDRINUSE") {
2007
- reportFailure(
2008
- "callback_port_in_use",
2009
- `Port ${CALLBACK_PORT} is in use \u2014 another 'prim auth login' may be running. Close it and retry.`
2010
- );
2011
- } else {
2012
- reportFailure(
2013
- "callback_bind_failed",
2014
- `Could not start the local callback server: ${err instanceof Error ? err.message : String(err)}`
2015
- );
2016
- }
2017
- return;
2018
- }
2019
- server.on("error", () => {
2020
- });
2021
- const authUrl = new URL(config.authorization_endpoint);
2022
- authUrl.searchParams.set("client_id", config.client_id);
2023
- authUrl.searchParams.set("redirect_uri", redirectUri);
2024
- authUrl.searchParams.set("response_type", "code");
2025
- authUrl.searchParams.set("provider", "authkit");
2026
- authUrl.searchParams.set("scope", config.default_scopes.join(" "));
2027
- authUrl.searchParams.set("state", state);
2028
- authUrl.searchParams.set("code_challenge", challenge);
2029
- authUrl.searchParams.set("code_challenge_method", "S256");
2030
- if (options.browser) {
2031
- console.error("Opening browser for authentication...");
2032
- openBrowser(authUrl.toString());
2033
- }
2034
- console.error(`If the browser doesn't open, visit:
2035
- ${authUrl.toString()}
2036
- `);
2037
- console.error("Waiting for callback...");
2038
- const timer = setTimeout(() => {
2039
- settle({ authenticated: false, error: "timeout", detail: "Authentication timed out." });
2040
- }, CALLBACK_TIMEOUT_MS);
2041
- timer.unref();
2042
- const result = await outcome;
2043
- clearTimeout(timer);
2044
- server.close();
2045
- if (!result.authenticated) {
2046
- reportFailure(result.error, result.detail);
2047
- return;
2048
- }
2049
- try {
2050
- const tokens = await exchangeCode(siteUrl, result.code, verifier, redirectUri);
2051
- await commitCredentials(tokens);
2052
- reportSuccess();
2053
- } catch (err) {
2054
- reportFailure("token_exchange_failed", err instanceof Error ? err.message : String(err));
2055
2275
  }
2056
2276
  });
2057
2277
  auth.command("set-token <token>").description("Save a bearer token for authenticated CLI calls").action(async (token) => {
@@ -2222,6 +2442,7 @@ function reportBinding(binding, installAttempted = false) {
2222
2442
  }
2223
2443
  process.stderr.write(
2224
2444
  installAttempted ? `[prim] GitHub repo connection could not be completed for ${binding.repositoryFullName}; the GitHub App was not granted admin access to that repository
2445
+ ` : isCloudMachineSession() ? `[prim] GitHub repo connection is required for ${binding.repositoryFullName} and cannot be completed from a Claude Code cloud session: ${CLOUD_GITHUB_CONNECT_REMEDY}
2225
2446
  ` : `[prim] GitHub repo connection is required for ${binding.repositoryFullName}; it enables repository-specific file attribution, Conflict Gate verification, and commit correlation. Starting GitHub App installation\u2026
2226
2447
  `
2227
2448
  );
@@ -2261,6 +2482,8 @@ async function runGithubConnect(dependencies = defaultDependencies2, options = {
2261
2482
  if (existing.status === "connected") {
2262
2483
  return { kind: "connected", binding: existing };
2263
2484
  }
2485
+ if (isCloudMachineSession())
2486
+ return { kind: "unbound", binding: existing, installAttempted: false };
2264
2487
  const start = await dependencies.createInstallIntent(client, {
2265
2488
  signal: AbortSignal.timeout(START_TIMEOUT_MS),
2266
2489
  now: dependencies.now
@@ -2904,7 +3127,10 @@ function registerHooksCommands(program2) {
2904
3127
 
2905
3128
  // src/commands/activation.ts
2906
3129
  var CONNECT_PROMPT = "[prim] GitHub repo connection is required to enable repository-specific file attribution, Conflict Gate verification, and commit correlation. Start the GitHub App connection now?";
2907
- var GITHUB_CONNECTION_REQUIRED = "GitHub repo connection is required before using Primitive in this repository. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation. Run `prim github connect` to complete it.";
3130
+ var GITHUB_CONNECTION_REQUIRED = "GitHub repo connection is required before using Primitive in this repository. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation.";
3131
+ function githubConnectionRequired() {
3132
+ return `${GITHUB_CONNECTION_REQUIRED} ${isCloudMachineSession() ? `It cannot be completed from a Claude Code cloud session: ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect` to complete it."}`;
3133
+ }
2908
3134
  function wireRepositoryHooks(root) {
2909
3135
  stageGitHookRuntime();
2910
3136
  refreshOwnedGlobalHooks();
@@ -2949,7 +3175,7 @@ function wireRepositoryHooks(root) {
2949
3175
  return { paths, changed };
2950
3176
  }
2951
3177
  async function maybeConnectRepository(root, globals) {
2952
- if (isNonInteractive(globals)) return void 0;
3178
+ if (isNonInteractive(globals) || isCloudMachineSession()) return void 0;
2953
3179
  const approved = Boolean(globals.yes) || await askConfirmation(CONNECT_PROMPT, process.stderr);
2954
3180
  if (!approved) return void 0;
2955
3181
  const outcome = await runGithubConnect(void 0, { root, browser: true });
@@ -2974,7 +3200,17 @@ function hookPathFields(paths) {
2974
3200
  ...paths["post-rewrite"] ? { postRewriteHook: paths["post-rewrite"] } : {}
2975
3201
  };
2976
3202
  }
3203
+ function projectScope(globals, active) {
3204
+ if (globals.scope === void 0) return false;
3205
+ if (globals.scope === "project") return true;
3206
+ process.stderr.write(
3207
+ `[prim] invalid --scope '${String(globals.scope)}': \`prim ${active ? "enable" : "disable"}\` accepts only 'project'
3208
+ `
3209
+ );
3210
+ process.exit(2);
3211
+ }
2977
3212
  async function applyActivation(active, globals = {}) {
3213
+ const project = projectScope(globals, active);
2978
3214
  const root = gitToplevel();
2979
3215
  if (!root) {
2980
3216
  process.stderr.write(
@@ -2983,12 +3219,14 @@ async function applyActivation(active, globals = {}) {
2983
3219
  );
2984
3220
  process.exit(1);
2985
3221
  }
2986
- let phase = active ? "post-commit hook coverage" : "local deactivation";
3222
+ let phase = "the repository's committed opt-out";
2987
3223
  try {
2988
3224
  let binding;
2989
3225
  let hookPaths = {};
2990
3226
  let hooksChanged = false;
2991
3227
  const wasActive = repoActiveFlag(root) === "true";
3228
+ const declaration = project ? planProjectInactiveDeclaration(root, !active) : void 0;
3229
+ phase = active ? "post-commit hook coverage" : "local deactivation";
2992
3230
  if (active) {
2993
3231
  ({ paths: hookPaths, changed: hooksChanged } = wireRepositoryHooks(root));
2994
3232
  phase = "GitHub repo connection";
@@ -2997,11 +3235,12 @@ async function applyActivation(active, globals = {}) {
2997
3235
  if (active && binding?.status === "unbound") {
2998
3236
  const connected = await maybeConnectRepository(root, globals);
2999
3237
  if (!connected) {
3000
- process.stderr.write(`[prim] ${GITHUB_CONNECTION_REQUIRED}
3238
+ process.stderr.write(`[prim] ${githubConnectionRequired()}
3001
3239
  `);
3002
3240
  printJson({
3003
3241
  active: false,
3004
3242
  repo: root,
3243
+ declaredInactive: declaresInactive(root),
3005
3244
  bindingStatus: binding.status,
3006
3245
  repositoryFullName: binding.repositoryFullName,
3007
3246
  ...hookPathFields(hookPaths)
@@ -3020,6 +3259,11 @@ async function applyActivation(active, globals = {}) {
3020
3259
  phase = "local activation";
3021
3260
  clearDemoPause(root);
3022
3261
  setRepoActive(root, active);
3262
+ markActivationExplicit(root);
3263
+ if (declaration) {
3264
+ phase = "the repository's committed opt-out";
3265
+ declaration.apply();
3266
+ }
3023
3267
  if (!active) clearHooksWired(root);
3024
3268
  if (active) {
3025
3269
  recordHooksWired(root, { onlyIfAbsent: wasActive && !hooksChanged });
@@ -3027,9 +3271,32 @@ async function applyActivation(active, globals = {}) {
3027
3271
  await daemonRequest("statusline_invalidate", {}, { timeoutMs: 250 });
3028
3272
  process.stderr.write(`[prim] prim ${active ? "enabled" : "disabled"} in ${root}
3029
3273
  `);
3274
+ const declaredInactive = declaresInactive(root);
3275
+ const ignored = Boolean(project && !active && isGitIgnored(root, ".claude/settings.json"));
3276
+ if (declaration?.changed)
3277
+ process.stderr.write(
3278
+ active ? `[prim] removed this repository's opt-out from ${declaration.path}; commit the change so new clones and Claude Code cloud sessions follow it
3279
+ ` : `[prim] recorded this repository's opt-out (PRIM_ACTIVE=false) in ${declaration.path}; commit it so prim stays off in every clone and every Claude Code cloud session, until someone runs \`prim enable\` there
3280
+ `
3281
+ );
3282
+ if (ignored)
3283
+ process.stderr.write(
3284
+ "[prim] this repository's .gitignore covers .claude/settings.json, so a plain `git add` skips it: stage it with `git add -f .claude/settings.json`, or the opt-out stays in this clone only\n"
3285
+ );
3286
+ else if (active && declaredInactive)
3287
+ process.stderr.write(
3288
+ "[prim] this repository commits an opt-out (PRIM_ACTIVE=false in .claude/settings.json): enabled for this clone only. `prim enable --scope project` removes the opt-out\n"
3289
+ );
3290
+ else if (!active && !declaredInactive && isPreparedCloudSession())
3291
+ process.stderr.write(
3292
+ "[prim] this lasts for this session's clone only: the next Claude Code cloud session starts from a fresh one. To keep prim off in this repository, run `prim disable --scope project` and commit .claude/settings.json\n"
3293
+ );
3030
3294
  printJson({
3031
3295
  active,
3032
3296
  repo: root,
3297
+ declaredInactive,
3298
+ ...declaration?.changed ? { settingsPath: declaration.path } : {},
3299
+ ...ignored ? { settingsIgnored: true } : {},
3033
3300
  ...binding ? {
3034
3301
  bindingStatus: binding.status,
3035
3302
  repositoryFullName: binding.repositoryFullName,
@@ -3048,8 +3315,14 @@ async function applyActivation(active, globals = {}) {
3048
3315
  }
3049
3316
  }
3050
3317
  function registerActivationCommands(program2) {
3051
- program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").action((_opts, command) => applyActivation(true, command.optsWithGlobals()));
3052
- program2.command("disable").description("Mute prim's hooks in this repo (git config prim.active=false)").action(
3318
+ program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").option(
3319
+ "--scope <scope>",
3320
+ "project: also remove the repository's committed opt-out from .claude/settings.json"
3321
+ ).action((_opts, command) => applyActivation(true, command.optsWithGlobals()));
3322
+ program2.command("disable").description("Mute prim's hooks in this repo (git config prim.active=false)").option(
3323
+ "--scope <scope>",
3324
+ "project: also record the opt-out in .claude/settings.json to commit, so it holds in every clone and Claude Code cloud session"
3325
+ ).action(
3053
3326
  (_opts, command) => applyActivation(false, command.optsWithGlobals())
3054
3327
  );
3055
3328
  }
@@ -3098,14 +3371,14 @@ async function inspectCodexHost(reload = false) {
3098
3371
  maxPayload: MAX_RESPONSE_BYTES,
3099
3372
  perMessageDeflate: false
3100
3373
  });
3101
- const finish = (value) => {
3374
+ const finish2 = (value) => {
3102
3375
  if (finished) return;
3103
3376
  finished = true;
3104
3377
  clearTimeout(timer);
3105
3378
  socket.terminate();
3106
3379
  resolve8(value);
3107
3380
  };
3108
- const fail = (reason) => finish({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
3381
+ const fail = (reason) => finish2({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
3109
3382
  const timer = setTimeout(() => fail("host-timeout"), TIMEOUT_MS);
3110
3383
  const request = (next, params) => {
3111
3384
  method = next;
@@ -3150,7 +3423,7 @@ async function inspectCodexHost(reload = false) {
3150
3423
  ) ? "review-required" : owned.every(
3151
3424
  (hook) => ["trusted", "managed"].includes(hook.trustStatus ?? "")
3152
3425
  ) ? "trusted" : "unknown";
3153
- finish({
3426
+ finish2({
3154
3427
  connection: "available",
3155
3428
  trust,
3156
3429
  reload: refreshed ? "refreshed" : "not-requested"
@@ -3224,7 +3497,7 @@ function applyUninstall(settings) {
3224
3497
  hooks[event] = list;
3225
3498
  }
3226
3499
  }
3227
- return { ...settings, hooks };
3500
+ return settings.hooks === void 0 ? settings : { ...settings, hooks };
3228
3501
  }
3229
3502
  function captureInstalled(settings) {
3230
3503
  return CODEX_CAPTURE_EVENTS.some(
@@ -3429,17 +3702,17 @@ async function runPinnedEnsure(options) {
3429
3702
  }
3430
3703
  const timer = setTimeout(() => {
3431
3704
  child.kill("SIGTERM");
3432
- finish(false);
3705
+ finish2(false);
3433
3706
  }, options.timeoutMs ?? LATEST_BOOTSTRAP_TIMEOUT_MS);
3434
- const finish = (result) => {
3707
+ const finish2 = (result) => {
3435
3708
  if (settled) return;
3436
3709
  settled = true;
3437
3710
  clearTimeout(timer);
3438
3711
  resolve8(result);
3439
3712
  };
3440
3713
  timer.unref();
3441
- child.once("error", () => finish(false));
3442
- child.once("exit", (code) => finish(code === 0));
3714
+ child.once("error", () => finish2(false));
3715
+ child.once("exit", (code) => finish2(code === 0));
3443
3716
  });
3444
3717
  }
3445
3718
  async function runLatestDaemonBootstrap(ensureCurrent, options = {}) {
@@ -5228,6 +5501,13 @@ async function detachedDaemonStatus() {
5228
5501
  { timeoutMs: STATUS_PROBE_TIMEOUT_MS }
5229
5502
  ) : null;
5230
5503
  const { json, exitCode } = classifyStatus(pidAlive, responding, snapshot, pid?.pid);
5504
+ if (!pidAlive && isClaudeCloudSession() && daemonExplicitlyDisabled()) {
5505
+ process.stderr.write(
5506
+ "[prim] daemon not used in Claude Code cloud sessions; capture delivers directly\n"
5507
+ );
5508
+ console.log(JSON.stringify({ ...json, disabled: true, cloudSession: true }, null, 2));
5509
+ return;
5510
+ }
5231
5511
  if (!pidAlive) {
5232
5512
  process.stderr.write("[prim] \u2717 daemon down\n");
5233
5513
  } else if (!responding) {
@@ -6351,6 +6631,99 @@ function formatRelateJson(result) {
6351
6631
  return JSON.stringify(result.outcome, null, 2);
6352
6632
  }
6353
6633
 
6634
+ // src/decisions/location-scope.ts
6635
+ var LocationScopeInputError = class extends Error {
6636
+ constructor(message) {
6637
+ super(message);
6638
+ this.name = "LocationScopeInputError";
6639
+ }
6640
+ };
6641
+ var MAX_LOCATION_SCOPE_SELECTORS = 25;
6642
+ var MAX_LOCATION_SCOPE_BRANCHES = 25;
6643
+ var MAX_BRANCH_PATTERN_CHARS = 255;
6644
+ var MAX_SHOWN_VALUE_CHARS = 80;
6645
+ function shown(value) {
6646
+ return JSON.stringify(
6647
+ value.length <= MAX_SHOWN_VALUE_CHARS ? value : `${value.slice(0, MAX_SHOWN_VALUE_CHARS - 1)}\u2026`
6648
+ );
6649
+ }
6650
+ function hasControlCharacter(value) {
6651
+ for (let index = 0; index < value.length; index += 1) {
6652
+ const code = value.charCodeAt(index);
6653
+ if (code <= 31 || code === 127) return true;
6654
+ }
6655
+ return false;
6656
+ }
6657
+ function isScopeBranchPattern(value) {
6658
+ return value.length > 0 && value.length <= MAX_BRANCH_PATTERN_CHARS && !hasControlCharacter(value);
6659
+ }
6660
+ function normalizeScopeDirectory(value) {
6661
+ const start = value.startsWith("./") ? 2 : 0;
6662
+ let end = value.length;
6663
+ while (end > start && value.charCodeAt(end - 1) === 47) end -= 1;
6664
+ return value.slice(start, end);
6665
+ }
6666
+ function scopeDirectories(values) {
6667
+ return values.map((value) => {
6668
+ const directory = normalizeScopeDirectory(value);
6669
+ if (directory === "." || directory === "" && value.startsWith("./")) {
6670
+ throw new LocationScopeInputError(
6671
+ `--scope-dir ${shown(value)} names the repository root; use --scope-repo to govern the whole repository`
6672
+ );
6673
+ }
6674
+ if (!isScopeDirectoryPrefix(directory)) {
6675
+ throw new LocationScopeInputError(
6676
+ `--scope-dir ${shown(value)} is not a repository-relative directory; use a path such as docs/ga: no leading "/", no "\\", no control character, no empty, "." or ".." segment, at most ${MAX_SCOPE_GLOB_CHARS} characters`
6677
+ );
6678
+ }
6679
+ return directory;
6680
+ });
6681
+ }
6682
+ function scopeGlobs(values) {
6683
+ for (const value of values) {
6684
+ if (!isScopeGlobPattern(value)) {
6685
+ throw new LocationScopeInputError(
6686
+ `--scope-glob ${shown(value)} is not an accepted glob; use a repository-relative pattern such as src/**/*.ts: no leading "/", no control character, no empty, "." or ".." segment, none of [ ] { } ! ( ) \\ ~ $ \`, at most ${MAX_SCOPE_GLOB_CHARS} characters`
6687
+ );
6688
+ }
6689
+ }
6690
+ return [...values];
6691
+ }
6692
+ function scopeBranches(values) {
6693
+ for (const value of values) {
6694
+ if (!isScopeBranchPattern(value)) {
6695
+ throw new LocationScopeInputError(
6696
+ `--scope-branch ${shown(value)} is not an accepted branch pattern; use a name or pattern such as main or release/*: not empty, no control character, at most ${MAX_BRANCH_PATTERN_CHARS} characters`
6697
+ );
6698
+ }
6699
+ }
6700
+ return [...values];
6701
+ }
6702
+ function locationScopeFromOptions(options) {
6703
+ const directories = scopeDirectories(options.scopeDir ?? []);
6704
+ const globs = scopeGlobs(options.scopeGlob ?? []);
6705
+ const branches = scopeBranches(options.scopeBranch ?? []);
6706
+ const selectorCount = (options.scopeRepo ? 1 : 0) + new Set(directories).size + new Set(globs).size;
6707
+ if (selectorCount > MAX_LOCATION_SCOPE_SELECTORS) {
6708
+ throw new LocationScopeInputError(
6709
+ `--scope-repo, --scope-dir and --scope-glob name ${selectorCount} distinct selectors; a Decision allows at most ${MAX_LOCATION_SCOPE_SELECTORS}`
6710
+ );
6711
+ }
6712
+ const branchCount = new Set(branches).size;
6713
+ if (branchCount > MAX_LOCATION_SCOPE_BRANCHES) {
6714
+ throw new LocationScopeInputError(
6715
+ `--scope-branch names ${branchCount} distinct branch patterns; a Decision allows at most ${MAX_LOCATION_SCOPE_BRANCHES}`
6716
+ );
6717
+ }
6718
+ const location = {
6719
+ ...options.scopeRepo ? { repository: true } : {},
6720
+ ...directories.length > 0 ? { directories } : {},
6721
+ ...globs.length > 0 ? { globs } : {},
6722
+ ...branches.length > 0 ? { branches } : {}
6723
+ };
6724
+ return Object.keys(location).length === 0 ? void 0 : location;
6725
+ }
6726
+
6354
6727
  // src/decisions/repairs.ts
6355
6728
  var REPAIRS_TIMEOUT_MS = 1e4;
6356
6729
  var MAX_REPAIR_LIST_PAGES = 100;
@@ -6907,7 +7280,7 @@ var DecisionRescopeResponseError = class extends Error {
6907
7280
  this.name = "DecisionRescopeResponseError";
6908
7281
  }
6909
7282
  };
6910
- function projectScope(scope) {
7283
+ function projectScope2(scope) {
6911
7284
  return {
6912
7285
  ...scope.scopeResolution === "unresolved" ? { scopeResolution: "unresolved" } : {},
6913
7286
  location: {
@@ -6924,7 +7297,7 @@ function projectScope(scope) {
6924
7297
  };
6925
7298
  }
6926
7299
  function projectSuccess2(response) {
6927
- const scope = projectScope(response.scope);
7300
+ const scope = projectScope2(response.scope);
6928
7301
  if (response.outcome === "no_op") {
6929
7302
  return {
6930
7303
  outcome: "no_op",
@@ -7346,14 +7719,10 @@ function rejectUserScope(command, error) {
7346
7719
  console.log(JSON.stringify({ ok: false, error: "invalid_user_scope" }, null, 2));
7347
7720
  process.exitCode = EXIT_USAGE;
7348
7721
  }
7349
- function locationScopeFromOptions(options) {
7350
- const location = {
7351
- ...options.scopeRepo ? { repository: true } : {},
7352
- ...options.scopeDir && options.scopeDir.length > 0 ? { directories: options.scopeDir } : {},
7353
- ...options.scopeGlob && options.scopeGlob.length > 0 ? { globs: options.scopeGlob } : {},
7354
- ...options.scopeBranch && options.scopeBranch.length > 0 ? { branches: options.scopeBranch } : {}
7355
- };
7356
- return Object.keys(location).length === 0 ? void 0 : location;
7722
+ function rejectLocationScope(command, error) {
7723
+ console.error(terminalSafeLine(`[prim] ${command} rejected: ${error.message}.`));
7724
+ console.log(JSON.stringify({ ok: false, error: "invalid_location_scope" }, null, 2));
7725
+ process.exitCode = EXIT_USAGE;
7357
7726
  }
7358
7727
  function registerDecisionsCommands(program2) {
7359
7728
  const decisions = program2.command("decisions").description("Inspect the project Decision Graph");
@@ -7606,7 +7975,16 @@ function registerDecisionsCommands(program2) {
7606
7975
  throw error;
7607
7976
  }
7608
7977
  const requestedFiles = opts.files ?? [];
7609
- const location = locationScopeFromOptions(opts);
7978
+ let location;
7979
+ try {
7980
+ location = locationScopeFromOptions(opts);
7981
+ } catch (error) {
7982
+ if (error instanceof LocationScopeInputError) {
7983
+ rejectLocationScope("create", error);
7984
+ return;
7985
+ }
7986
+ throw error;
7987
+ }
7610
7988
  let explicitScope = {};
7611
7989
  if (requestedFiles.length > 0 || location !== void 0) {
7612
7990
  const binding = repoSyncId(process.cwd());
@@ -7739,7 +8117,16 @@ function registerDecisionsCommands(program2) {
7739
8117
  }
7740
8118
  throw error;
7741
8119
  }
7742
- const location = locationScopeFromOptions(opts);
8120
+ let location;
8121
+ try {
8122
+ location = locationScopeFromOptions(opts);
8123
+ } catch (error) {
8124
+ if (error instanceof LocationScopeInputError) {
8125
+ rejectLocationScope("rescope", error);
8126
+ return;
8127
+ }
8128
+ throw error;
8129
+ }
7743
8130
  const hasLocationSelector = location !== void 0;
7744
8131
  const hasNonLocationScope = time !== void 0 || users !== void 0;
7745
8132
  process.exitCode = await rescopeDecision({
@@ -9118,7 +9505,12 @@ function classifyDoctor(checks) {
9118
9505
  }
9119
9506
  function classifyAuthCredential(credential, expiresAt, hasRefresh) {
9120
9507
  if (!credential) {
9121
- return { name: "auth", status: "fail", detail: "no token \u2014 run `prim auth login`" };
9508
+ return {
9509
+ name: "auth",
9510
+ status: "fail",
9511
+ // `prim auth login` is refused in a cloud session; name what works there.
9512
+ detail: isClaudeCloudSession() ? `no credentials \u2014 ${CLOUD_CREDENTIALS_REMEDY}` : "no token \u2014 run `prim auth login`"
9513
+ };
9122
9514
  }
9123
9515
  if (credential.source !== "token_file") {
9124
9516
  return { name: "auth", status: "ok", detail: "valid fixed bearer credential" };
@@ -9143,7 +9535,7 @@ async function checkAuth() {
9143
9535
  return {
9144
9536
  name: "auth",
9145
9537
  status: status2.authenticated ? "ok" : "fail",
9146
- detail: status2.authenticated ? `machine ${status2.displayName ?? status2.machineId} \xB7 ${status2.storageBackend} \xB7 expires in ${Math.round((status2.accessTokenExpiresInMs ?? 0) / 1e3)}s` : `machine authentication: ${status2.recoveryReason}; unlock the credential store or run prim auth configure-machine`
9538
+ detail: status2.authenticated ? `machine ${status2.displayName ?? status2.machineId} \xB7 ${status2.storageBackend} \xB7 ${status2.tokenHeldByProxy ? "token held by the environment's proxy" : `expires in ${Math.round((status2.accessTokenExpiresInMs ?? 0) / 1e3)}s`}` : `machine authentication: ${status2.recoveryReason}. ${status2.recoveryDetail ? stripControlChars(status2.recoveryDetail) : "Unlock the credential store or run prim auth configure-machine."}`
9147
9539
  };
9148
9540
  }
9149
9541
  } catch {
@@ -9163,6 +9555,12 @@ async function checkAuth() {
9163
9555
  }
9164
9556
  function classifyDaemonHealth(snapshot, options = {}) {
9165
9557
  if (options.disabled) {
9558
+ if (isClaudeCloudSession())
9559
+ return {
9560
+ name: "daemon",
9561
+ status: "ok",
9562
+ detail: "not used in Claude Code cloud sessions; capture delivers directly"
9563
+ };
9166
9564
  return {
9167
9565
  name: "daemon",
9168
9566
  status: "fail",
@@ -9410,19 +9808,20 @@ async function checkJournalOrganization() {
9410
9808
  }
9411
9809
  function classifyRepositoryBinding(value, current, active) {
9412
9810
  const connectionCapabilities = "It enables repository-specific file attribution, Conflict Gate verification, and commit correlation.";
9811
+ const cloud = isCloudMachineSession();
9413
9812
  if (current.status === "unbound") {
9414
9813
  if (!active) {
9415
9814
  return {
9416
9815
  name: "github-repo-connection",
9417
9816
  status: "fail",
9418
- detail: `GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} Run \`prim github connect\`, then \`prim enable\`.`
9817
+ detail: `GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} ${cloud ? `To complete it, ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect`, then `prim enable`."}`
9419
9818
  };
9420
9819
  }
9421
9820
  const localDetail = value === void 0 ? "GitHub repo connection is not complete" : isValidRepoSyncId(value) ? "server reports GitHub repo connection is not complete; the last connection state is retained locally for recovery" : "server reports GitHub repo connection is not complete; the local cached connection state is invalid";
9422
9821
  return {
9423
9822
  name: "github-repo-connection",
9424
9823
  status: "warn",
9425
- detail: `${localDetail} \u2014 GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} Run \`prim github connect\` to complete it.`
9824
+ detail: `${localDetail} \u2014 GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} ${cloud ? `To complete it, ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect` to complete it."}`
9426
9825
  };
9427
9826
  }
9428
9827
  if (!isValidRepoSyncId(value)) {
@@ -10485,6 +10884,21 @@ var HTTP_SERVER_ERROR_MIN = 500;
10485
10884
  function isDomainRejection(err) {
10486
10885
  return err instanceof HttpError && err.status >= HTTP_CLIENT_ERROR_MIN && err.status < HTTP_SERVER_ERROR_MIN;
10487
10886
  }
10887
+ var MAX_REFUSAL_FIELD_CHARS = 500;
10888
+ function capped(value) {
10889
+ return value.length <= MAX_REFUSAL_FIELD_CHARS ? value : `${value.slice(0, MAX_REFUSAL_FIELD_CHARS - 1)}\u2026`;
10890
+ }
10891
+ function serverRefusal(error) {
10892
+ if (!(error instanceof HttpError) || !isCliErrorResponse(error.body)) return {};
10893
+ const { error: code, message } = error.body;
10894
+ return {
10895
+ error: capped(code),
10896
+ ...typeof message === "string" ? { message: capped(message) } : {}
10897
+ };
10898
+ }
10899
+ function machineScopeRemedy() {
10900
+ return isCloudMachineSession() ? "This Claude Code cloud session's credential is not permitted to record a resolution. Recording an outcome does not bypass the gate or change a Decision; continue without the record." : "This credential is not permitted to record a resolution.";
10901
+ }
10488
10902
  async function performReconcile(idOrShortId, opts = {}) {
10489
10903
  if (opts.check !== void 0 || opts.outcome !== void 0) {
10490
10904
  await performResolution(idOrShortId, opts);
@@ -10529,9 +10943,17 @@ async function performResolution(idOrShortId, opts) {
10529
10943
  `);
10530
10944
  } catch (error) {
10531
10945
  const status2 = error instanceof HttpError ? error.status : void 0;
10532
- process.stderr.write(`[prim] resolution failed${status2 ? ` (${status2})` : ""}
10946
+ const refusal = serverRefusal(error);
10947
+ const detail = [refusal.error, refusal.message].map((value) => boundedHealthError(value)).filter(Boolean).join(": ");
10948
+ process.stderr.write(
10949
+ `[prim] resolution failed${status2 ? ` (${status2})` : ""}${detail ? `: ${detail}` : ""}
10950
+ `
10951
+ );
10952
+ if (status2 === 403 && refusal.error === "machine_scope_required") {
10953
+ process.stderr.write(`[prim] ${machineScopeRemedy()}
10533
10954
  `);
10534
- console.log(JSON.stringify({ ok: false, status: status2 }));
10955
+ }
10956
+ console.log(JSON.stringify({ ok: false, status: status2, ...refusal }));
10535
10957
  process.exitCode = isDomainRejection(error) ? EXIT_USAGE2 : EXIT_SERVER;
10536
10958
  }
10537
10959
  }
@@ -10607,14 +11029,301 @@ function registerSessionCommands(program2) {
10607
11029
  });
10608
11030
  }
10609
11031
 
11032
+ // src/commands/setup-cloud.ts
11033
+ var EXIT_INCOMPLETE = 1;
11034
+ var EXIT_USAGE3 = 2;
11035
+ function refuseOutsideCloud(deps, mode) {
11036
+ const env = deps.env ?? process.env;
11037
+ if (isClaudeCloudSession(env)) return false;
11038
+ if (mode === "prepare" && (deps.platform ?? process.platform) === "linux") return false;
11039
+ refuse(
11040
+ deps,
11041
+ mode,
11042
+ mode === "prepare" ? "cloud \xB7 refusing: --prepare is for a Claude Code cloud environment's setup script (a Linux VM); on this machine it would disable the daemon" : "cloud \xB7 refusing: this is not a Claude Code cloud session (CLAUDE_CODE_REMOTE is not true); on this machine it would disable the daemon. Run `prim setup` instead"
11043
+ );
11044
+ return true;
11045
+ }
11046
+ function refuse(deps, mode, reason) {
11047
+ deps.note(reason);
11048
+ printJson({
11049
+ ok: false,
11050
+ cloud: mode,
11051
+ results: { cloud: "missing" },
11052
+ failed: ["cloud"],
11053
+ remedies: [reason],
11054
+ instructions: "Cloud setup does not apply on this machine. Tell the user why in one sentence."
11055
+ });
11056
+ deps.exit(EXIT_USAGE3);
11057
+ }
11058
+ function prepareCloudImage(deps) {
11059
+ if (refuseOutsideCloud(deps, "prepare")) return;
11060
+ const env = deps.env ?? process.env;
11061
+ if (!isClaudeCloudSession(env) && (deps.developerInstall ?? hasDeveloperUserInstall)()) {
11062
+ refuse(
11063
+ deps,
11064
+ "prepare",
11065
+ "cloud \xB7 refusing: this machine has its own user-scope prim install; --prepare is for a Claude Code cloud environment's setup script"
11066
+ );
11067
+ return;
11068
+ }
11069
+ const results = {};
11070
+ const remedies = [];
11071
+ const origin = prepareOrigin(deps);
11072
+ prepareSteps(deps, results, remedies, origin);
11073
+ if (origin === "session" && results.prepared === "ok") {
11074
+ const reason = "image \xB7 not prepared by this run: it ran inside a running Claude Code session, so only this VM is wired. Claude Code loads the hooks when it next starts here, and new sessions start from the environment's image. If the environment's setup script does not run `prim setup --cloud --prepare` yet, add it there; sessions started after that load the hooks";
11075
+ deps.note(reason);
11076
+ remedies.push(reason);
11077
+ results.image = "missing";
11078
+ }
11079
+ finish(deps, "prepare", results, remedies);
11080
+ }
11081
+ function prepareOrigin(deps) {
11082
+ const env = deps.env ?? process.env;
11083
+ if (!insideClaudeCode(env)) return "image";
11084
+ const live = isPreparedCloudSession(env) && !preparedInSession(env) && (deps.userHooksComplete ?? cloudUserInstallComplete)();
11085
+ return live ? "image" : "session";
11086
+ }
11087
+ function setupCloudSession(deps) {
11088
+ if (refuseOutsideCloud(deps, "session")) return;
11089
+ const results = {};
11090
+ const remedies = [];
11091
+ const outcome = {};
11092
+ sessionSteps(deps, results, remedies, {}, outcome);
11093
+ finish(deps, "session", results, remedies, outcome.optedOut);
11094
+ }
11095
+ function setupDetectedCloudSession(deps) {
11096
+ const env = deps.env ?? process.env;
11097
+ deps.note("cloud \xB7 Claude Code cloud session detected; running cloud setup");
11098
+ const results = {};
11099
+ const remedies = [];
11100
+ const root = gitToplevel(deps.cwd);
11101
+ let preparedNow = false;
11102
+ if (!isPreparedCloudSession(env) && !(root && hasProjectPrimInstall(root)) && !(root && optsOut(root))) {
11103
+ prepareSteps(deps, results, remedies, "session");
11104
+ preparedNow = results.prepared === "ok";
11105
+ }
11106
+ const outcome = {};
11107
+ sessionSteps(deps, results, remedies, { preparedNow }, outcome);
11108
+ finish(deps, "session", results, remedies, outcome.optedOut);
11109
+ }
11110
+ function optsOut(root) {
11111
+ return declaresInactive(root) && !explicitlyActive(root);
11112
+ }
11113
+ function prepareSteps(deps, results, remedies, origin = "image") {
11114
+ const env = deps.env ?? process.env;
11115
+ clearCloudPrepared(env);
11116
+ const attempt = (key, label2, action) => {
11117
+ deps.note(`${label2} \xB7 installing\u2026`);
11118
+ try {
11119
+ action();
11120
+ results[key] = "ok";
11121
+ } catch (error) {
11122
+ const reason = `${label2} \xB7 ${error instanceof Error ? error.message : String(error)}`;
11123
+ deps.note(reason);
11124
+ remedies.push(reason);
11125
+ results[key] = "failed";
11126
+ }
11127
+ };
11128
+ attempt("runtime", "hook runtime", deps.stage ?? stageHookRuntime);
11129
+ attempt(
11130
+ "userHooks",
11131
+ "Claude Code hooks (user scope)",
11132
+ deps.installUserHooks ?? (() => {
11133
+ performCloudUserInstall();
11134
+ })
11135
+ );
11136
+ const step = (key, label2, args) => {
11137
+ deps.note(`${label2}\u2026`);
11138
+ results[key] = deps.run(args).code === 0 ? "ok" : "failed";
11139
+ if (results[key] === "failed")
11140
+ remedies.push(`${key} \xB7 failed; run \`prim ${args.join(" ")}\` to see why`);
11141
+ };
11142
+ step("preauth", "pre-authorize \xB7 writing prim allow-rule (user scope)", [
11143
+ "claude",
11144
+ "preauth",
11145
+ "--scope",
11146
+ "user"
11147
+ ]);
11148
+ step("skill", "agent skill \xB7 installing", [
11149
+ "skill",
11150
+ "install",
11151
+ "--agent",
11152
+ "claude",
11153
+ "--scope",
11154
+ "user"
11155
+ ]);
11156
+ step("daemon", "daemon \xB7 recording the opt-out", ["daemon", "stop"]);
11157
+ if (results.runtime === "ok" && results.userHooks === "ok")
11158
+ attempt(
11159
+ "prepared",
11160
+ "cloud activation",
11161
+ () => (deps.markPrepared ?? ((from) => markCloudPrepared(env, from)))(origin)
11162
+ );
11163
+ }
11164
+ function credentialsReady({ deps, results, remedy, env }) {
11165
+ let machine;
11166
+ try {
11167
+ machine = hasMachineConfiguration({ env });
11168
+ } catch (error) {
11169
+ remedy(`credentials \xB7 ${error instanceof MachineAuthError ? error.message : String(error)}`);
11170
+ results.credentials = "failed";
11171
+ return false;
11172
+ }
11173
+ if (!machine && !resolveStoredCredential(env)) {
11174
+ remedy(
11175
+ `credentials \xB7 missing: ${CLOUD_CREDENTIALS_REMEDY}; the environment must also allow ${cloudAllowedDomains(void 0, void 0, env).join(" and ")} under Allowed domains (blocked by default)`
11176
+ );
11177
+ results.credentials = "missing";
11178
+ return false;
11179
+ }
11180
+ clearMachineCooldowns(primConfigDirectory({ env }));
11181
+ const status2 = deps.run(["auth", "status", "--json"], true);
11182
+ const auth = deps.parseAuthStatus(status2);
11183
+ if (auth !== "valid") {
11184
+ const detail = authFailureDetail(status2.stdout);
11185
+ remedy(
11186
+ auth === "unreachable" ? unreachableRemedy(detail, env) : machine ? `credentials \xB7 ${detail ?? "rejected"}${// Guidance that already names the replacement needs no second copy.
11187
+ detail?.includes("prim auth enroll") ? "" : "; if the credential itself was revoked, mint a replacement with `prim auth enroll --new-installation` and revoke the old installation in Settings \u2192 Developer installations"}` : (
11188
+ // A fixed token or stored sign-in has no installation to revoke.
11189
+ `credentials \xB7 the sign-in was rejected: ${CLOUD_CREDENTIALS_REMEDY}`
11190
+ )
11191
+ );
11192
+ results.credentials = "failed";
11193
+ return false;
11194
+ }
11195
+ if (enrollmentRequired(status2.stdout)) {
11196
+ remedy(
11197
+ `credentials \xB7 this sign-in can only enroll an installation, which a cloud session cannot do: ${CLOUD_CREDENTIALS_REMEDY}`
11198
+ );
11199
+ results.credentials = "failed";
11200
+ return false;
11201
+ }
11202
+ results.credentials = "ok";
11203
+ return true;
11204
+ }
11205
+ function repositoryRoot({ deps, results, remedy }, outcome) {
11206
+ const root = gitToplevel(deps.cwd);
11207
+ if (!root) {
11208
+ remedy("repository \xB7 not a git repository; run from the cloned repository");
11209
+ results.repository = "missing";
11210
+ return void 0;
11211
+ }
11212
+ if (optsOut(root)) {
11213
+ deps.note(
11214
+ "repository \xB7 opted out: its .claude/settings.json declares PRIM_ACTIVE=false, so prim stays off here. `prim enable` turns it on for this session's clone; `prim enable --scope project` removes the opt-out"
11215
+ );
11216
+ results.repository = "ok";
11217
+ outcome.optedOut = true;
11218
+ return void 0;
11219
+ }
11220
+ if (!githubRepositoryFullName(root)) {
11221
+ remedy(`repository \xB7 ${repositoryIdentityRemedy(root)}`);
11222
+ results.repository = "missing";
11223
+ return void 0;
11224
+ }
11225
+ return root;
11226
+ }
11227
+ function sessionHooks({ deps, results, remedy, env }, root, options) {
11228
+ const pendingHooks = options.preparedNow === true || preparedInSession(env);
11229
+ if (root !== void 0 && hasProjectPrimInstall(root) || !pendingHooks && isPreparedCloudSession(env) && (deps.userHooksComplete ?? cloudUserInstallComplete)()) {
11230
+ results.session = "ok";
11231
+ } else if (pendingHooks) {
11232
+ remedy(
11233
+ "session hooks \xB7 wired in this VM, but Claude Code loads them only when it next starts here, and new sessions start from the environment's image: add `prim setup --cloud --prepare` to the environment's setup script"
11234
+ );
11235
+ results.session = "missing";
11236
+ } else {
11237
+ remedy(
11238
+ `session hooks \xB7 none: run \`prim setup --cloud --prepare\` in the environment's setup script${// Outside a repository there is nothing to commit an install to.
11239
+ root === void 0 ? "" : ", or commit `prim claude install --scope project` in this repository"}`
11240
+ );
11241
+ results.session = "missing";
11242
+ }
11243
+ }
11244
+ function sessionSteps(deps, results, remedies, options = {}, outcome = {}) {
11245
+ const remedy = (message) => {
11246
+ deps.note(message);
11247
+ remedies.push(message);
11248
+ };
11249
+ const check = { deps, results, remedy, env: deps.env ?? process.env };
11250
+ const credentials = credentialsReady(check);
11251
+ const root = repositoryRoot(check, outcome);
11252
+ if (!outcome.optedOut) sessionHooks(check, root ?? gitToplevel(deps.cwd) ?? void 0, options);
11253
+ if (!credentials || !root) return;
11254
+ const step = (key, label2, args) => {
11255
+ if (label2) deps.note(`${label2} \xB7 installing\u2026`);
11256
+ results[key] = deps.run(args).code === 0 ? "ok" : "failed";
11257
+ if (results[key] === "failed")
11258
+ remedy(`${label2 || key} \xB7 failed; run \`prim ${args.join(" ")}\` to see why`);
11259
+ };
11260
+ if (results.daemon === void 0) step("daemon", "", ["daemon", "stop"]);
11261
+ step("hooks", "git hooks", ["hooks", "install"]);
11262
+ deps.note("activate this repo \xB7 installing\u2026");
11263
+ const enabled = deps.run(["enable", "--non-interactive"]);
11264
+ results.enable = enabled.code === 0 ? "ok" : "failed";
11265
+ if (results.enable === "failed") {
11266
+ const unconnected = unconnectedRepository(enabled.stdout);
11267
+ remedy(
11268
+ unconnected ? `repository \xB7 ${unconnected} is not connected to Primitive: ${isCloudMachineSession(deps.env ?? process.env) ? CLOUD_GITHUB_CONNECT_REMEDY : "run `prim github connect --no-browser` and open the link it prints"}` : "activate this repo \xB7 failed; run `prim enable --non-interactive` to see why"
11269
+ );
11270
+ }
11271
+ }
11272
+ function unreachableRemedy(detail, env) {
11273
+ if (detail?.startsWith(SERVER_WAIT_PREFIX)) return `credentials \xB7 ${detail}`;
11274
+ if (detail?.includes("Allowed domains"))
11275
+ return `credentials \xB7 ${detail}; prim needs ${cloudAllowedDomains(void 0, void 0, env).join(" and ")} allowed`;
11276
+ return `credentials \xB7 Primitive is unreachable from this environment: ${cloudEgressRemedy()}${detail ? ` (${detail})` : ""}`;
11277
+ }
11278
+ function unconnectedRepository(stdout) {
11279
+ try {
11280
+ const parsed = JSON.parse(stdout || "{}");
11281
+ return parsed.bindingStatus === "unbound" && typeof parsed.repositoryFullName === "string" ? stripControlChars(parsed.repositoryFullName) : void 0;
11282
+ } catch {
11283
+ return void 0;
11284
+ }
11285
+ }
11286
+ function enrollmentRequired(stdout) {
11287
+ try {
11288
+ return JSON.parse(stdout || "{}").enrollmentRequired === true;
11289
+ } catch {
11290
+ return false;
11291
+ }
11292
+ }
11293
+ function authFailureDetail(stdout) {
11294
+ try {
11295
+ const parsed = JSON.parse(stdout || "{}");
11296
+ return typeof parsed.recoveryDetail === "string" ? stripControlChars(parsed.recoveryDetail).replace(CLOUD_SETUP_POINTER, "").replace(/\.$/u, "") : void 0;
11297
+ } catch {
11298
+ return void 0;
11299
+ }
11300
+ }
11301
+ function finish(deps, mode, results, remedies, optedOut = false) {
11302
+ const failed = Object.keys(results).filter((key) => results[key] !== "ok");
11303
+ deps.note(
11304
+ failed.length === 0 ? `cloud ${mode} complete` : `cloud ${mode} incomplete (${failed.join(", ")})`
11305
+ );
11306
+ const instructions = failed.length === 0 ? mode === "prepare" ? "The cloud environment is prepared; sessions started from it load prim's hooks." : optedOut ? "This repository opts out of Primitive (PRIM_ACTIVE=false in its .claude/settings.json), so nothing was activated. Tell the user in one sentence, then continue their task; do not run prim enable unless they ask." : "Primitive is set up in this Claude Code cloud session. Tell the user in one sentence, then continue their task. There is no welcome or demo in cloud sessions." : "Cloud setup is incomplete. Tell the user each remedy in one sentence before continuing; do not run prim auth login or prim auth enroll, which cannot work in a cloud session.";
11307
+ printJson({
11308
+ ok: failed.length === 0,
11309
+ cloud: mode,
11310
+ results,
11311
+ failed,
11312
+ remedies,
11313
+ instructions,
11314
+ ...optedOut ? { optedOut: true } : {}
11315
+ });
11316
+ if (failed.length) deps.exit(EXIT_INCOMPLETE);
11317
+ }
11318
+
10610
11319
  // src/commands/setup.ts
10611
11320
  import { spawnSync as spawnSync2 } from "child_process";
10612
11321
  import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
10613
11322
  import { homedir as homedir7 } from "os";
10614
11323
  import { join as join16, resolve as resolve5, sep } from "path";
10615
- var EXIT_INCOMPLETE = 1;
11324
+ var EXIT_INCOMPLETE2 = 1;
10616
11325
  var GITHUB_CONNECT_TIMEOUT_MS = 9e4;
10617
- var EXIT_USAGE3 = 2;
11326
+ var EXIT_USAGE4 = 2;
10618
11327
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
10619
11328
  var SETUP_DAEMON_DRAINS_ENV = "PRIM_SETUP_DAEMON_DRAINS";
10620
11329
  function setupStepSpawnOptions(capture, env = process.env, options = {}) {
@@ -10788,7 +11497,7 @@ function parseSetupAuthStatus(result) {
10788
11497
  if (parsed.status === "invalid") return "invalid";
10789
11498
  } catch {
10790
11499
  }
10791
- return result.code === EXIT_USAGE3 ? "unreachable" : "invalid";
11500
+ return result.code === EXIT_USAGE4 ? "unreachable" : "invalid";
10792
11501
  }
10793
11502
  function registerSetupCommand(program2, dependencies = {}) {
10794
11503
  program2.command("setup").description(
@@ -10803,7 +11512,13 @@ function registerSetupCommand(program2, dependencies = {}) {
10803
11512
  ).option(
10804
11513
  "--migrate",
10805
11514
  "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
10806
- ).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").action((opts) => {
11515
+ ).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").option(
11516
+ "--cloud",
11517
+ "set up a Claude Code cloud session with machine credentials: git hooks and activation only, no daemon or onboarding"
11518
+ ).option(
11519
+ "--prepare",
11520
+ "with --cloud, prepare the environment's image from its setup script: hook runtime, user-scope Claude hooks, activation (no credentials or network)"
11521
+ ).action((opts, command) => {
10807
11522
  const setupAt = Date.now();
10808
11523
  const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
10809
11524
  if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
@@ -10811,18 +11526,38 @@ function registerSetupCommand(program2, dependencies = {}) {
10811
11526
  `[prim] unknown --agent "${agentInput}" (expected claude, codex, cursor, or hermes)
10812
11527
  `
10813
11528
  );
10814
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
11529
+ (dependencies.exit ?? process.exit)(EXIT_USAGE4);
10815
11530
  return;
10816
11531
  }
10817
11532
  if (opts.scope !== "project" && opts.scope !== "user") {
10818
11533
  process.stderr.write(`[prim] unknown --scope "${opts.scope}" (expected project or user)
10819
11534
  `);
10820
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
11535
+ (dependencies.exit ?? process.exit)(EXIT_USAGE4);
11536
+ return;
11537
+ }
11538
+ const cloudSetup = opts.cloud === true || isClaudeCloudSession();
11539
+ if (opts.prepare && !opts.cloud) {
11540
+ process.stderr.write("[prim] --prepare applies only with --cloud\n");
11541
+ (dependencies.exit ?? process.exit)(EXIT_USAGE4);
11542
+ return;
11543
+ }
11544
+ const cloudConflicts = cloudSetup ? [
11545
+ opts.agent !== void 0 && agentInput !== "claude" ? "--agent" : void 0,
11546
+ command.getOptionValueSource("scope") === "cli" ? "--scope" : void 0,
11547
+ opts.globalHooksPath ? "--global-hooks-path" : void 0,
11548
+ opts.migrate ? "--migrate" : void 0
11549
+ ].filter((flag) => flag !== void 0) : [];
11550
+ if (cloudConflicts.length) {
11551
+ process.stderr.write(
11552
+ `[prim] ${opts.cloud ? "--cloud" : "setup in a Claude Code cloud session"} does not combine with ${cloudConflicts.join(", ")}
11553
+ `
11554
+ );
11555
+ (dependencies.exit ?? process.exit)(EXIT_USAGE4);
10821
11556
  return;
10822
11557
  }
10823
11558
  if (opts.globalHooksPath && opts.scope !== "user") {
10824
11559
  process.stderr.write("[prim] --global-hooks-path applies only with --scope user\n");
10825
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
11560
+ (dependencies.exit ?? process.exit)(EXIT_USAGE4);
10826
11561
  return;
10827
11562
  }
10828
11563
  const agent = agentInput;
@@ -10833,7 +11568,8 @@ function registerSetupCommand(program2, dependencies = {}) {
10833
11568
  const childArgs = opts.details ? args.filter((arg) => arg !== "--compact") : args;
10834
11569
  const r = spawnSync2(process.execPath, [self, ...childArgs], {
10835
11570
  ...setupStepSpawnOptions(capture, process.env, {
10836
- startsDaemon: opts.daemon,
11571
+ // Cloud setup stops the daemon, so its steps drain for themselves.
11572
+ startsDaemon: opts.daemon && !cloudSetup,
10837
11573
  compact: true
10838
11574
  }),
10839
11575
  timeout: timeoutMs2
@@ -10852,6 +11588,13 @@ function registerSetupCommand(program2, dependencies = {}) {
10852
11588
  `);
10853
11589
  });
10854
11590
  const exit = dependencies.exit ?? process.exit;
11591
+ if (cloudSetup) {
11592
+ const cloud = { run, note, exit, parseAuthStatus: parseSetupAuthStatus };
11593
+ if (opts.prepare) prepareCloudImage(cloud);
11594
+ else if (opts.cloud) setupCloudSession(cloud);
11595
+ else setupDetectedCloudSession(cloud);
11596
+ return;
11597
+ }
10855
11598
  if (detected && agent !== "claude") {
10856
11599
  note(`agent \xB7 detected ${agent} session (override with --agent <agent>)`);
10857
11600
  }
@@ -10860,14 +11603,14 @@ function registerSetupCommand(program2, dependencies = {}) {
10860
11603
  let authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
10861
11604
  if (authStatus === "unreachable") {
10862
11605
  note("auth \xB7 verification unavailable; no setup changes were made");
10863
- exit(EXIT_USAGE3);
11606
+ exit(EXIT_USAGE4);
10864
11607
  return;
10865
11608
  }
10866
11609
  if (authStatus === "invalid" && machine) {
10867
11610
  note(
10868
11611
  "auth \xB7 machine credentials need attention; run prim auth status, then configure-machine with administrator-issued credentials"
10869
11612
  );
10870
- exit(EXIT_INCOMPLETE);
11613
+ exit(EXIT_INCOMPLETE2);
10871
11614
  return;
10872
11615
  }
10873
11616
  if (authStatus === "invalid") {
@@ -10875,7 +11618,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10875
11618
  const login = run(["auth", "login"]);
10876
11619
  if (login.code !== 0) {
10877
11620
  note("auth \xB7 login failed; no integration changes were made");
10878
- exit(EXIT_INCOMPLETE);
11621
+ exit(EXIT_INCOMPLETE2);
10879
11622
  return;
10880
11623
  }
10881
11624
  authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
@@ -10883,7 +11626,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10883
11626
  note(
10884
11627
  authStatus === "unreachable" ? "auth \xB7 login completed but verification is unavailable; no integration changes were made" : "auth \xB7 login did not produce valid credentials; no integration changes were made"
10885
11628
  );
10886
- exit(authStatus === "unreachable" ? EXIT_USAGE3 : EXIT_INCOMPLETE);
11629
+ exit(authStatus === "unreachable" ? EXIT_USAGE4 : EXIT_INCOMPLETE2);
10887
11630
  return;
10888
11631
  }
10889
11632
  } else {
@@ -10900,7 +11643,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10900
11643
  note(
10901
11644
  "auth \xB7 installation enrollment failed; existing credentials and captured activity were preserved. Run prim auth enroll for details."
10902
11645
  );
10903
- exit(EXIT_INCOMPLETE);
11646
+ exit(EXIT_INCOMPLETE2);
10904
11647
  return;
10905
11648
  }
10906
11649
  const payload = setupChildPayload(enrollment.stdout);
@@ -10982,7 +11725,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10982
11725
  failed: failed2,
10983
11726
  health
10984
11727
  });
10985
- if (failed2.length) exit(EXIT_INCOMPLETE);
11728
+ if (failed2.length) exit(EXIT_INCOMPLETE2);
10986
11729
  return;
10987
11730
  }
10988
11731
  if (welcomeHandoff) {
@@ -11021,7 +11764,7 @@ function registerSetupCommand(program2, dependencies = {}) {
11021
11764
  instructions: "Read the file at welcomeSkill and follow it."
11022
11765
  }
11023
11766
  });
11024
- exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE);
11767
+ exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE2);
11025
11768
  return;
11026
11769
  }
11027
11770
  const installationSucceeded = !Object.values(results).includes("failed");
@@ -11091,7 +11834,7 @@ function registerSetupCommand(program2, dependencies = {}) {
11091
11834
  welcome: setupChildPayload(welcomeResult.stdout),
11092
11835
  ...onboarding ? { onboarding, nextAction: onboarding.nextAction } : {}
11093
11836
  });
11094
- exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
11837
+ exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE2);
11095
11838
  });
11096
11839
  }
11097
11840
  function primCommand(argv = process.argv, version = packageVersion()) {
@@ -11177,7 +11920,7 @@ function registerStatuslineCommands(program2) {
11177
11920
 
11178
11921
  // src/commands/uninstall.ts
11179
11922
  import { spawnSync as spawnSync3 } from "child_process";
11180
- var EXIT_INCOMPLETE2 = 1;
11923
+ var EXIT_INCOMPLETE3 = 1;
11181
11924
  var CHILD_TIMEOUT_MS = 3e4;
11182
11925
  var UNINSTALL_ORCHESTRATOR_ENV = "PRIM_UNINSTALL_ORCHESTRATOR";
11183
11926
  function planUninstallSteps(inRepository) {
@@ -11305,7 +12048,7 @@ function registerUninstallCommand(program2, dependencies = {}) {
11305
12048
  });
11306
12049
  const detail = result2.error?.message ?? result2.stderr ?? "";
11307
12050
  return {
11308
- code: result2.status ?? EXIT_INCOMPLETE2,
12051
+ code: result2.status ?? EXIT_INCOMPLETE3,
11309
12052
  stdout: result2.stdout ?? "",
11310
12053
  stderr: detail
11311
12054
  };
@@ -11380,7 +12123,7 @@ function registerUninstallCommand(program2, dependencies = {}) {
11380
12123
  note(
11381
12124
  complete ? "uninstall complete \xB7 credentials and pending journals preserved" : `uninstall incomplete \xB7 failed: ${failed.join(", ")}`
11382
12125
  );
11383
- exit(complete ? 0 : EXIT_INCOMPLETE2);
12126
+ exit(complete ? 0 : EXIT_INCOMPLETE3);
11384
12127
  });
11385
12128
  }
11386
12129
 
@@ -11814,7 +12557,7 @@ function runStartupBackgroundWork(argv, env, work) {
11814
12557
  const uninstall2 = command === "uninstall" || env[UNINSTALL_ORCHESTRATOR_ENV] === "1";
11815
12558
  if (uninstall2 || command === "demo") return;
11816
12559
  work.notify();
11817
- const setupDaemonDrains = command === "setup" && !args.includes("--no-daemon") || env[SETUP_DAEMON_DRAINS_ENV] === "1";
12560
+ const setupDaemonDrains = command === "setup" && !args.includes("--no-daemon") && !args.includes("--cloud") && !isClaudeCloudSession(env) || env[SETUP_DAEMON_DRAINS_ENV] === "1";
11818
12561
  if (!setupDaemonDrains && (command !== "moves" || subcommand !== "flush")) work.flush();
11819
12562
  if (mayHealDaemon(argv, env)) work.healDaemon();
11820
12563
  }