passport-bridge 0.15.0 → 0.16.0

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 (53) hide show
  1. package/README.md +16 -0
  2. package/dist/cliArgs.d.ts +1 -1
  3. package/dist/cliArgs.js +8 -2
  4. package/dist/cliAutopilot.d.ts +6 -1
  5. package/dist/cliAutopilot.js +43 -16
  6. package/dist/cliAutopilotPolicy.d.ts +33 -1
  7. package/dist/cliAutopilotPolicy.js +34 -1
  8. package/dist/cliEnv.d.ts +40 -0
  9. package/dist/cliEnv.js +157 -0
  10. package/dist/cliExec.d.ts +23 -2
  11. package/dist/cliExec.js +51 -7
  12. package/dist/cliHook.d.ts +8 -0
  13. package/dist/cliHook.js +11 -6
  14. package/dist/cliHookClassify.d.ts +7 -0
  15. package/dist/cliHookClassify.js +22 -2
  16. package/dist/cliHookDecide.d.ts +3 -2
  17. package/dist/cliHookDecide.js +13 -2
  18. package/dist/cliHookEnvironment.d.ts +9 -3
  19. package/dist/cliHookEnvironment.js +69 -15
  20. package/dist/cliHookGuard.d.ts +26 -2
  21. package/dist/cliHookGuard.js +72 -17
  22. package/dist/cliHookLocal.js +9 -3
  23. package/dist/cliHookVendors.js +8 -2
  24. package/dist/cliHookVendorsMore.d.ts +21 -0
  25. package/dist/cliHookVendorsMore.js +196 -0
  26. package/dist/cliOutput.js +4 -0
  27. package/dist/cliPolicyV2.js +90 -3
  28. package/dist/cliUndo.d.ts +49 -0
  29. package/dist/cliUndo.js +312 -0
  30. package/dist/completion.js +5 -1
  31. package/dist/envDatabase.d.ts +28 -0
  32. package/dist/envDatabase.js +166 -0
  33. package/dist/envLinkFs.d.ts +57 -0
  34. package/dist/envLinkFs.js +140 -0
  35. package/dist/envLinksCloud.d.ts +31 -0
  36. package/dist/envLinksCloud.js +233 -0
  37. package/dist/envLinksHosting.d.ts +33 -0
  38. package/dist/envLinksHosting.js +463 -0
  39. package/dist/envResolve.d.ts +48 -0
  40. package/dist/envResolve.js +221 -0
  41. package/dist/envTarget.d.ts +61 -0
  42. package/dist/envTarget.js +50 -0
  43. package/dist/execBackupTarget.d.ts +25 -0
  44. package/dist/execBackupTarget.js +201 -0
  45. package/dist/initAutopilotStep.js +44 -3
  46. package/dist/initState.d.ts +3 -0
  47. package/dist/passport.js +7 -7
  48. package/dist/pluginPin.d.ts +1 -1
  49. package/dist/pluginPin.js +1 -1
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. package/npm-shrinkwrap.json +2 -2
  53. package/package.json +1 -1
package/README.md CHANGED
@@ -67,6 +67,7 @@ passport run github_search_issues '{"query":"SSO"}'
67
67
  | `wait <approval-id> [--timeout <s>]` | Wait for a person to decide an approval request (default 100 seconds). |
68
68
  | `rules test "<command>" [--environment <kind>]` | What Autopilot decides for a command, why, and which environment it acts on. |
69
69
  | `sessions [--status running\|idle\|ended]` | Your agents' recent sessions with what Passport decided. |
70
+ | `undo <action-id>\|--last [--option <id>] [--yes]` | Undo an action Passport took a backup before, within 7 days. See [Undo](#undo). |
70
71
  | `setup --org <pek_key> [--yes] [--clients <list>]` | Set up every agent on this computer for your company without asking anything (MDM and scripts). See [Company rollout](#company-rollout). |
71
72
  | `setup` | Install and maintain assigned team workflows as managed skills. |
72
73
  | `session` | Run NDJSON commands over one authenticated MCP session. |
@@ -248,8 +249,11 @@ passport rules test "rm -rf ~/"
248
249
  passport wait apr_123
249
250
  passport sessions
250
251
  passport sync # or: passport sync --remove
252
+ passport env # or: passport env set railway qa staging
251
253
  ```
252
254
 
255
+ - `env` lists where commands in this folder land, read the way each vendor's own CLI reads it (`src/envResolve.ts`; order: flag, the folder's link, the vendor's default, the workspace's saved mapping, the whole-word naming rule, else Production). Link readers: `src/envLinksHosting.ts` (Railway `~/.railway/config.json`, Vercel `.vercel/project.json` / `repo.json`, Supabase `supabase/.temp/project-ref`, Wrangler config, Netlify `.netlify/state.json`, Firebase `.firebaserc` + configstore, Convex `CONVEX_DEPLOYMENT`, Neon `.neon`), `src/envLinksCloud.ts` (Fly, Heroku git remotes, kubeconfig, AWS profile, gcloud configuration, Terraform workspace, Stripe key mode), and `src/envDatabase.ts` (database URLs: only `DATABASE_URL`, `DIRECT_URL`, `POSTGRES_URL*`, `DATABASE_URL_UNPOOLED`, reduced to a host-derived key; the URL, user, and password never leave the function). Files are read fresh for every command, size-capped, and a link file symlinked out of the project is ignored (`src/envLinkFs.ts`). A name in a link file never loosens anything: an unplaced id is Production, and for a placed id its mapping decides while a different name is treated as a rename (sent as the new label, which the server stores). Findings to a server that sends `resources` in cli-policy v2 carry `{kind, source, resourceKey?, label?, platform?, flag?, via}`. `env set` calls `PUT /api/my/environments/:platform/:key`; members may only say Production.
256
+
253
257
  - `rules test` classifies the command here and sends only its app and verb (and the environment kind) to `POST /api/my/rules/test`, never the command line. An everyday command goes as a finding (`{finding: {vendor, verb, risk, environment}}`), because only this computer can place its paths. It prints the decision, its cause, the environment, and the class. Without a server answer it decides from this computer's copy and says how old it is. `--environment` picks one when the flags don't say.
254
258
  - `wait` long-polls `GET /api/my/approvals/<id>/wait`. Approved: `Approved by Ramish. Run the command again.` (exit 0). Declined: the note for the agent, `Declined by Ramish: <note>` (exit 5, cause `approval_denied`). Expired: `Expired. The agent can ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout` (default 100 seconds, under an agent's 2-minute command limit): exit 4 with the same command as `next`.
255
259
  - `sessions` lists recent sessions (`GET /api/my/agent-sessions`): status, agent, folder, start, `42 ran · 2 asked · 1 blocked`, environments touched, and `Waiting for you` when approvals are pending.
@@ -271,6 +275,17 @@ passport exec -- railway up -e staging
271
275
  - Asks wait for your approval in Passport (web or push) when you're at the keyboard or with `--wait <sec>`; otherwise exit 4 with the approval id: run `passport wait <id>`, then the command again. An approval is used once. Blocked or declined: exit 5. No key, or it stopped working: exit 3 ("Your Railway key in Passport stopped working. Update it in Apps."). Offline: exit 1, nothing runs, and exec never uses a key on this computer instead.
272
276
  - In Claude Code, the guard rewrites a plain vendor command whose key is in Passport to `passport exec` (PreToolUse `updatedInput` with allow; a block stays a deny). When the rules ask, or someone is at the keyboard, the rewrite adds `--wait 120`, so the agent holds while the person approves: "Approve it on your phone or in Passport." Codex and Cursor get no rewrite: use `passport exec` there.
273
277
  - Cloud agents (Agents → Cloud agents) run exec and MCP with `PASSPORT_AGENT_KEY` and `PASSPORT_ENDPOINT`: the owner's rules decide, the owner's keys are used, and approvals go to the owner.
278
+ - Backups: for `gh issue close`, `gh pr close`, `gh api -X DELETE` of a branch, `vercel env rm`, `vercel rollback`, and `vercel promote`, exec also sends the ids Passport needs to take a backup first (repo and number or branch; the linked Vercel project and variable name from `.vercel/project.json`), never a value. After the run it prints `Backup taken. Undo within 7 days: passport undo <action-id>`, or `No backup: <reason>` for a delete it couldn't back up.
279
+
280
+ ### Undo
281
+
282
+ ```sh
283
+ passport undo act_123
284
+ passport undo --last --yes
285
+ ```
286
+
287
+ - Shows what comes back and what won't, how old the backup is, and how long undo stays available, then asks `Undo it? [y/N]` (and which option, when there are several). Without a terminal it prints the preview and `passport undo <id> --yes`; `--option <id>` picks an option.
288
+ - Passport decides an undo from the CLI like a change in that environment. Asks first: exit 4 with the approval id; run `passport wait <id>`, then the undo again. Blocked or declined: exit 5. Done: exit 0, with each step (`✓`/`✗`). Partly done or failed: exit 1. Expired, already undone, or otherwise unavailable: exit 5 with the reason. No backup: exit 6. Needs a member profile.
274
289
 
275
290
  ### Persistent sessions
276
291
 
@@ -385,6 +400,7 @@ With `--json`, stdout is exactly one JSON value; hints and warnings go to stderr
385
400
  | `wait` | `{approvalId,status:"approved",scope?,message}`; declined, expired, and still-waiting are errors with `approvalId` |
386
401
  | `rules` | `{command,decision,cause?,explanation?,environment?,environmentAssumed?,actionClass?,source}` |
387
402
  | `sessions` | `{sessions:[{id,client,folder,status,startedAt,lastActivityAt,counts,environments,waiting}],nextCursor}` |
403
+ | `undo` | `{actionId,status,message,steps:[{label,ok,detail?}],option,undoActionId?}`; without `--yes` off a terminal, `{actionId,status:"preview",preview,next}`; pending, blocked, and declined are errors |
388
404
  | `doctor` | `{version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}`, also on failure |
389
405
  | `ready` | `{ready,version,ok,auth,profile?,profileCount,endpointOrigin?,server?,checks}` |
390
406
  | `search` | Gateway payload with `results` or `catalog`, and `note` |
package/dist/cliArgs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "sessions", "sync", "exec", "keys", "setup", "session", "access", "completion", "help", "version"];
1
+ export declare const COMMANDS: readonly ["init", "login", "logout", "profiles", "use", "status", "doctor", "ready", "search", "describe", "run", "connect", "resources", "prompts", "discover", "scan", "hook", "wait", "rules", "sessions", "env", "sync", "exec", "undo", "keys", "setup", "session", "access", "completion", "help", "version"];
2
2
  export type Command = (typeof COMMANDS)[number];
3
3
  export declare class ArgError extends Error {
4
4
  }
package/dist/cliArgs.js CHANGED
@@ -19,8 +19,10 @@ export const COMMANDS = [
19
19
  "wait",
20
20
  "rules",
21
21
  "sessions",
22
+ "env",
22
23
  "sync",
23
24
  "exec",
25
+ "undo",
24
26
  "keys",
25
27
  "setup",
26
28
  "session",
@@ -42,7 +44,7 @@ const FLAGS = {
42
44
  apply: { kind: "boolean", commands: ["setup", "hook"] },
43
45
  guard: { kind: "boolean", commands: ["hook"] },
44
46
  "no-open": { kind: "boolean", commands: ["login", "init"] },
45
- yes: { kind: "boolean", commands: ["init", "setup", "keys"] },
47
+ yes: { kind: "boolean", commands: ["init", "setup", "keys", "undo"] },
46
48
  org: { kind: "value", commands: ["setup"] },
47
49
  clients: { kind: "value", commands: ["setup"] },
48
50
  "skip-apps": { kind: "boolean", commands: ["init"] },
@@ -68,7 +70,9 @@ const FLAGS = {
68
70
  "client-id": { kind: "value", commands: ["access"] },
69
71
  environment: { kind: "value", commands: ["rules"] },
70
72
  status: { kind: "value", commands: ["sessions"] },
71
- remove: { kind: "boolean", commands: ["sync"] }
73
+ remove: { kind: "boolean", commands: ["sync"] },
74
+ last: { kind: "boolean", commands: ["undo"] },
75
+ option: { kind: "value", commands: ["undo"] }
72
76
  };
73
77
  export class ArgError extends Error {
74
78
  }
@@ -179,7 +183,9 @@ function validateShape(command, positionals) {
179
183
  wait: 1,
180
184
  rules: 2,
181
185
  sessions: 0,
186
+ env: 4,
182
187
  sync: 0,
188
+ undo: 1,
183
189
  keys: 2,
184
190
  setup: 3,
185
191
  session: 0,
@@ -15,6 +15,8 @@ import { type Preset, type PresetRow } from "./cliAutopilotPolicy.js";
15
15
  import { type MemberApi } from "./cliClient.js";
16
16
  import { type LocalMachine } from "./cliHookLocal.js";
17
17
  import { type EnvKind } from "./cliHookEnvironment.js";
18
+ import { type LinkFs } from "./envLinkFs.js";
19
+ export { env } from "./cliEnv.js";
18
20
  import { type CommandResult, type Runtime } from "./cliSupport.js";
19
21
  /** Long enough to be useful, short enough for an agent's default 2-minute
20
22
  * command timeout. */
@@ -24,7 +26,11 @@ export type AutopilotDependencies = {
24
26
  now?: () => number;
25
27
  /** The machine `rules test` reads paths on; tests pass a pretend one. */
26
28
  machine?: LocalMachine;
29
+ /** Where folder links are read from; tests pass a pretend one. */
30
+ linkFs?: LinkFs;
27
31
  };
32
+ export declare function api(args: ParsedArgs, runtime: Runtime, deps: AutopilotDependencies, waitMs?: number, agentKeyOk?: boolean): MemberApi;
33
+ export declare function json<T>(response: Response, fallback: string): Promise<T>;
28
34
  export declare function wait(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
29
35
  export declare function rules(args: ParsedArgs, runtime: Runtime, deps?: AutopilotDependencies): Promise<CommandResult>;
30
36
  type SessionRow = {
@@ -74,4 +80,3 @@ export declare function localMidnight(now: number): number;
74
80
  /** Read presets and floors for `passport status`. Never throws. */
75
81
  export declare function autopilotStatus(fetchApi: (path: string, init: RequestInit) => Promise<Response>, profile: string | undefined, signal: AbortSignal, now?: number): Promise<AutopilotStatus>;
76
82
  export declare function autopilotLines(status: AutopilotStatus): string[];
77
- export {};
@@ -14,8 +14,12 @@ import { bool, value } from "./cliArgs.js";
14
14
  import { OTHER_APPS, PRESET_LABEL, PRESET_ROWS, rowLabel } from "./cliAutopilotPolicy.js";
15
15
  import { memberApi } from "./cliClient.js";
16
16
  import { classifyLine, localMachine } from "./cliHookLocal.js";
17
- import { ENV_KINDS, ENV_LABEL, environmentHintWith, isEnvKind } from "./cliHookEnvironment.js";
17
+ import { ENV_KINDS, ENV_LABEL, isEnvKind } from "./cliHookEnvironment.js";
18
18
  import { decideGuard, guardLabel } from "./cliHookGuard.js";
19
+ import { NODE_LINK_FS } from "./envLinkFs.js";
20
+ import { resolveTarget } from "./envResolve.js";
21
+ // `passport env` lives in cliEnv.ts; the dispatcher reaches it through here.
22
+ export { env } from "./cliEnv.js";
19
23
  import { readCliPolicy } from "./cliPolicy.js";
20
24
  import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, sanitize, sleep, timeoutMs } from "./cliSupport.js";
21
25
  /** Long enough to be useful, short enough for an agent's default 2-minute
@@ -23,7 +27,7 @@ import { callerFrom, failure, readBoundedJson, resolveCliAuth, safeApiError, san
23
27
  export const WAIT_DEFAULT_SECONDS = 100;
24
28
  const WAIT_POLL_SECONDS = 30;
25
29
  const APPROVAL_ID = /^[A-Za-z0-9_-]{1,80}$/;
26
- function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
30
+ export function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
27
31
  if (deps.api)
28
32
  return deps.api;
29
33
  const auth = resolveCliAuth(args, runtime.env);
@@ -39,7 +43,7 @@ function api(args, runtime, deps, waitMs = 0, agentKeyOk = false) {
39
43
  signal: runtime.signal
40
44
  });
41
45
  }
42
- async function json(response, fallback) {
46
+ export async function json(response, fallback) {
43
47
  if (response.status === 401 || response.status === 403) {
44
48
  return failure(await safeApiError(response, "Passport refused this profile."), 2, "auth", {
45
49
  hint: "Run: passport login"
@@ -68,14 +72,19 @@ function waitOutcome(id, body) {
68
72
  if (status === "allowed" || status === "approved") {
69
73
  // "Approved by Ramish." or "Now allowed by your rules.", then the next step.
70
74
  const lead = message ?? `Approved${by ? ` by ${by}` : ""}.`;
71
- const human = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
75
+ const next = /run the command again/i.test(lead) ? lead : `${lead} Run the command again.`;
76
+ // Once, when this approval reaches the threshold: "Tip: You've approved
77
+ // railway redeploy in Staging 5 times. ... Make it a rule: <link>".
78
+ const suggestion = text(body.suggestion, 400);
79
+ const human = suggestion ? `${next}\n${suggestion}` : next;
72
80
  return {
73
81
  json: {
74
82
  approvalId: id,
75
83
  status: "approved",
76
84
  ...(scope ? { scope } : {}),
77
85
  ...(by ? { decidedBy: by } : {}),
78
- message: human
86
+ message: next,
87
+ ...(suggestion ? { suggestion } : {})
79
88
  },
80
89
  human,
81
90
  essential: true
@@ -187,8 +196,8 @@ function inEnvironment(findings, environment) {
187
196
  ? { ...finding, local: { ...finding.local, environment } }
188
197
  : { ...finding, pushEnvironment: undefined, args: [...(finding.args ?? []), "--environment", environment] });
189
198
  }
190
- function localTest(command, findings, complete, policy) {
191
- const decision = decideGuard(findings, policy, command, complete);
199
+ function localTest(command, findings, complete, policy, machine) {
200
+ const decision = decideGuard(findings, policy, command, complete, machine);
192
201
  if (!decision)
193
202
  return null;
194
203
  return {
@@ -203,15 +212,13 @@ function localTest(command, findings, complete, policy) {
203
212
  * What `rules test` sends: an everyday command as what it is (program, verb,
204
213
  * class, place), never its words; a vendor command as its label.
205
214
  */
206
- function testBody(lead, label, cached, environment) {
215
+ function testBody(lead, label, target, environment) {
207
216
  if (lead.local) {
208
217
  const finding = { vendor: lead.vendor, verb: lead.verb ?? "invoke", risk: lead.risk };
209
218
  return { finding: { ...finding, environment: environment ?? lead.local.environment } };
210
219
  }
211
- const hint = lead.vendor
212
- ? environmentHintWith(lead.vendor, lead.args ?? [], cached?.version === 2 ? { flags: cached.autopilot.environmentFlags, known: cached.autopilot.environments } : {})
213
- : undefined;
214
- const placed = environment ?? lead.pushEnvironment ?? (hint && hint.source !== "assumed" ? hint.kind : undefined);
220
+ // Where this computer placed it: a flag, the folder's link, or a mapping.
221
+ const placed = environment ?? lead.pushEnvironment ?? (target && target.source !== "assumed" ? target.kind : undefined);
215
222
  return { command: label, ...(placed ? { environment: placed } : {}) };
216
223
  }
217
224
  /** The workspace's answer, or null to decide on this computer. */
@@ -249,7 +256,19 @@ export async function rules(args, runtime, deps = {}) {
249
256
  }
250
257
  const environment = environmentFlag;
251
258
  // Paths are read where you run this, like the hook reads the agent's folder.
252
- const line = classifyLine(command, deps.machine ?? localMachine(process.cwd(), runtime.env));
259
+ const machine = deps.machine ?? localMachine(process.cwd(), runtime.env);
260
+ const line = classifyLine(command, machine);
261
+ // Folder links are read here too, unless a test gave a pretend machine only.
262
+ const guardMachine = deps.machine && !deps.linkFs
263
+ ? undefined
264
+ : {
265
+ cwd: machine.cwd,
266
+ rawCwd: deps.machine ? machine.cwd : process.cwd(),
267
+ projectRoot: machine.projectRoot,
268
+ home: machine.home,
269
+ env: runtime.env,
270
+ fs: deps.linkFs ?? NODE_LINK_FS
271
+ };
253
272
  const all = inEnvironment(line.findings, environment);
254
273
  const findings = all.filter((finding) => finding.vendor);
255
274
  if (!findings.length) {
@@ -269,13 +288,21 @@ export async function rules(args, runtime, deps = {}) {
269
288
  }
270
289
  })();
271
290
  const cached = profile ? readCliPolicy(profile) : null;
272
- const decided = decideGuard(all, cached, command, line.complete);
291
+ const decided = decideGuard(all, cached, command, line.complete, guardMachine);
273
292
  // The command that decides: the strictest one the rules spoke about.
274
293
  const lead = decided?.findings[0] ?? findings[0];
275
294
  const label = guardLabel(lead);
276
- const local = localTest(command, all, line.complete, cached);
295
+ const local = localTest(command, all, line.complete, cached, guardMachine);
296
+ const v2 = cached?.version === 2 ? cached.autopilot : undefined;
297
+ const target = decided?.decided?.find((entry) => entry.finding === lead)?.target ??
298
+ (lead.vendor && !lead.local
299
+ ? resolveTarget(lead.vendor, lead.args ?? [], {
300
+ ...(v2 ? { flags: v2.environmentFlags, known: v2.environments } : {}),
301
+ ...(v2?.resources ? { resources: v2.resources } : {})
302
+ })
303
+ : undefined);
277
304
  // The server knows grants, every rule, and the workspace's environments.
278
- const asked = profile || deps.api ? await askServer(testBody(lead, label, cached, environment), args, runtime, deps) : null;
305
+ const asked = profile || deps.api ? await askServer(testBody(lead, label, target, environment), args, runtime, deps) : null;
279
306
  let result = asked;
280
307
  let source = result ? "Decided by your workspace's rules." : "";
281
308
  if (!result) {
@@ -39,6 +39,20 @@ export type CliRule = {
39
39
  owner?: string;
40
40
  /** The server's whole cause line, used as is when present. */
41
41
  label?: string;
42
+ /** Actions an approved exception lifts this rule for (this person only). */
43
+ except?: RuleException[];
44
+ };
45
+ export type RuleException = {
46
+ vendor?: string;
47
+ verb?: string;
48
+ appKey?: string;
49
+ actionClass?: ActionClass;
50
+ environment: ActionEnv | "any";
51
+ };
52
+ /** The second-person rule's cause lines, as the server words them. */
53
+ export declare const SECOND_PERSON_LABEL: {
54
+ readonly change: "Production changes need someone else to approve";
55
+ readonly delete: "Production deletes need someone else to approve";
42
56
  };
43
57
  /** A flag that names an environment: `--prod` names one itself, `--environment`
44
58
  * takes the name as its value. */
@@ -73,6 +87,21 @@ export type AutopilotPolicy = {
73
87
  /** The server decides everyday commands too (Phase 1.5): reports and
74
88
  * decide requests may carry them. */
75
89
  localCommands?: boolean;
90
+ /** Production classes someone else must approve: never run here, and never
91
+ * approved in the agent's own prompt. "Maya or Sam" names who approves. */
92
+ secondPerson?: {
93
+ classes: ActionClass[];
94
+ approvers: string;
95
+ };
96
+ /** Resources the workspace placed, by id (Phase 4.5). Present only when the
97
+ * server reads where a finding lands, so findings may carry it. */
98
+ resources?: Array<{
99
+ platform: string;
100
+ resourceKey: string;
101
+ label: string;
102
+ kind: EnvKind;
103
+ source: "detected" | "set" | "assumed";
104
+ }>;
76
105
  };
77
106
  /** The platform a vendor CLI acts on, so its rules and environments line up
78
107
  * with the same platform's MCP app (server `cliPlatform`). */
@@ -101,6 +130,9 @@ export type LocalDecision = {
101
130
  decision: Decision;
102
131
  cause: Cause;
103
132
  };
104
- /** The server's `decideAction`, minus grants (only the server knows them). */
133
+ /** The server's `decideAction`, minus grants (only the server knows them).
134
+ * The second-person rule turns a Production run into an ask the server owns. */
105
135
  export declare function decideAction(policy: AutopilotPolicy, facts: ActionFacts): LocalDecision;
136
+ /** Whether an ask needs someone other than the person at the keyboard. */
137
+ export declare function needsSecondPerson(cause: Cause | undefined): boolean;
106
138
  export declare function decisionRank(decision: Decision): number;
@@ -14,6 +14,11 @@
14
14
  import { ENV_LABEL } from "./cliHookEnvironment.js";
15
15
  export const PRESETS = ["careful", "balanced", "handsoff"];
16
16
  export const ACTION_CLASSES = ["read", "change", "delete", "irreversible"];
17
+ /** The second-person rule's cause lines, as the server words them. */
18
+ export const SECOND_PERSON_LABEL = {
19
+ change: "Production changes need someone else to approve",
20
+ delete: "Production deletes need someone else to approve"
21
+ };
17
22
  /** The platform a vendor CLI acts on, so its rules and environments line up
18
23
  * with the same platform's MCP app (server `cliPlatform`). */
19
24
  export function platformOf(vendor) {
@@ -112,8 +117,22 @@ function ruleMatches(rule, facts) {
112
117
  }
113
118
  if (rule.decision === "allow" && facts.actionClass === "irreversible" && level !== LEVEL_ACTION)
114
119
  return false;
120
+ // An approved exception lifts this rule for the action it names.
121
+ if (rule.except?.some((lift) => exceptionCovers(lift, facts)))
122
+ return false;
115
123
  return true;
116
124
  }
125
+ function exceptionCovers(lift, facts) {
126
+ if (lift.environment !== "any" && lift.environment !== facts.environment)
127
+ return false;
128
+ if (lift.vendor !== undefined && lift.verb !== undefined)
129
+ return lift.vendor === facts.vendor && lift.verb === facts.verb;
130
+ if (lift.appKey !== undefined && !appMatches(lift.appKey, facts))
131
+ return false;
132
+ if (lift.actionClass !== undefined && lift.actionClass !== facts.actionClass)
133
+ return false;
134
+ return lift.appKey !== undefined || lift.actionClass !== undefined;
135
+ }
117
136
  function matchText(rule) {
118
137
  if (rule.vendor !== undefined && rule.verb !== undefined)
119
138
  return `${rule.vendor} ${rule.verb}`;
@@ -173,8 +192,22 @@ function mostSpecific(rules) {
173
192
  function stricter(a, b) {
174
193
  return DECISION_RANK[b] > DECISION_RANK[a] ? b : a;
175
194
  }
176
- /** The server's `decideAction`, minus grants (only the server knows them). */
195
+ /** The server's `decideAction`, minus grants (only the server knows them).
196
+ * The second-person rule turns a Production run into an ask the server owns. */
177
197
  export function decideAction(policy, facts) {
198
+ const decided = decideByRules(policy, facts);
199
+ const classes = policy.secondPerson?.classes ?? [];
200
+ if (decided.decision !== "allow" || facts.environment !== "production" || !classes.includes(facts.actionClass)) {
201
+ return decided;
202
+ }
203
+ const label = facts.actionClass === "change" ? SECOND_PERSON_LABEL.change : SECOND_PERSON_LABEL.delete;
204
+ return { decision: "ask", cause: { kind: "floor", label } };
205
+ }
206
+ /** Whether an ask needs someone other than the person at the keyboard. */
207
+ export function needsSecondPerson(cause) {
208
+ return cause?.label === SECOND_PERSON_LABEL.change || cause?.label === SECOND_PERSON_LABEL.delete;
209
+ }
210
+ function decideByRules(policy, facts) {
178
211
  const matching = policy.rules.filter((rule) => ruleMatches(rule, facts));
179
212
  // 1. Block rules, any scope. The most specific one names the cause.
180
213
  const blocks = matching.filter((rule) => rule.decision === "block");
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `passport env`: where commands in this folder land, the way each vendor's
3
+ * own CLI would decide it (Autopilot Phase 4.5).
4
+ *
5
+ * passport env [--json]
6
+ * passport env set <vendor> <resource> <production|staging|development>
7
+ *
8
+ * Read on this computer. Rows name the vendor, the resource's label, how
9
+ * Passport knows (linked, a flag, the vendor's default), and its kind; never a
10
+ * path, URL, or key. `env set` places a resource for the whole workspace:
11
+ * admins may choose any kind, everyone else only Production.
12
+ */
13
+ import { type ParsedArgs } from "./cliArgs.js";
14
+ import { type MemberApi } from "./cliClient.js";
15
+ import { type LocalMachine } from "./cliHookLocal.js";
16
+ import { type LinkFs } from "./envLinkFs.js";
17
+ import { type DetectedLink } from "./envResolve.js";
18
+ import { type CommandResult, type Runtime } from "./cliSupport.js";
19
+ export type EnvDependencies = {
20
+ api?: MemberApi;
21
+ machine?: LocalMachine;
22
+ linkFs?: LinkFs;
23
+ cwd?: string;
24
+ };
25
+ export type EnvRow = {
26
+ vendor: string;
27
+ resource: string;
28
+ how: string;
29
+ kind: string;
30
+ assumed: boolean;
31
+ note?: string;
32
+ };
33
+ /** One row per linked vendor, as the table and `--json` show it. */
34
+ export declare function envRows(links: DetectedLink[]): EnvRow[];
35
+ /** The links in this folder, placed with this computer's copy of the rules. */
36
+ export declare function linksHere(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): DetectedLink[];
37
+ export declare const ENV_EMPTY = "No linked apps in this folder.";
38
+ /** The Environments table `init` shows for this project. */
39
+ export declare function envTableLines(rows: EnvRow[]): string[];
40
+ export declare function env(args: ParsedArgs, runtime: Runtime, deps?: EnvDependencies): Promise<CommandResult>;
package/dist/cliEnv.js ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `passport env`: where commands in this folder land, the way each vendor's
3
+ * own CLI would decide it (Autopilot Phase 4.5).
4
+ *
5
+ * passport env [--json]
6
+ * passport env set <vendor> <resource> <production|staging|development>
7
+ *
8
+ * Read on this computer. Rows name the vendor, the resource's label, how
9
+ * Passport knows (linked, a flag, the vendor's default), and its kind; never a
10
+ * path, URL, or key. `env set` places a resource for the whole workspace:
11
+ * admins may choose any kind, everyone else only Production.
12
+ */
13
+ import { value } from "./cliArgs.js";
14
+ import { memberApi } from "./cliClient.js";
15
+ import { platformOf } from "./cliAutopilotPolicy.js";
16
+ import { ENV_LABEL, isEnvKind } from "./cliHookEnvironment.js";
17
+ import { localMachine } from "./cliHookLocal.js";
18
+ import { readCliPolicy } from "./cliPolicy.js";
19
+ import { NODE_LINK_FS } from "./envLinkFs.js";
20
+ import { detectLinks } from "./envResolve.js";
21
+ import { vendorName } from "./envTarget.js";
22
+ import { callerFrom, failure, resolveCliAuth, safeApiError, timeoutMs } from "./cliSupport.js";
23
+ const HOW = {
24
+ flag: "flag",
25
+ linked: "linked",
26
+ "vendor-default": "default",
27
+ mapping: "placed",
28
+ name: "name",
29
+ assumed: "linked"
30
+ };
31
+ /** One row per linked vendor, as the table and `--json` show it. */
32
+ export function envRows(links) {
33
+ return links.map(({ vendor, target }) => {
34
+ const assumed = target.source === "assumed";
35
+ return {
36
+ vendor: vendorName(vendor),
37
+ resource: target.label ?? target.name ?? "-",
38
+ how: target.problem ? "unreadable" : HOW[target.source],
39
+ kind: target.kind,
40
+ assumed,
41
+ ...(target.problem
42
+ ? { note: target.problem }
43
+ : assumed
44
+ ? { note: "Not placed yet, so Passport treats it as Production." }
45
+ : {})
46
+ };
47
+ });
48
+ }
49
+ function table(rows) {
50
+ const cells = rows.map((row) => [
51
+ row.vendor,
52
+ row.resource,
53
+ row.how,
54
+ `${ENV_LABEL[row.kind] ?? row.kind}${row.assumed ? " (assumed)" : ""}`
55
+ ]);
56
+ const header = ["App", "Resource", "How", "Environment"];
57
+ const widths = header.map((title, index) => Math.max(title.length, ...cells.map((cell) => cell[index].length)));
58
+ const line = (cell) => cell
59
+ .map((part, index) => part.padEnd(widths[index]))
60
+ .join(" ")
61
+ .trimEnd();
62
+ return [line(header), ...cells.map(line)].join("\n");
63
+ }
64
+ function whereHere(runtime, deps) {
65
+ const cwd = deps.cwd ?? process.cwd();
66
+ const machine = deps.machine ?? localMachine(cwd, runtime.env);
67
+ return {
68
+ cwd: machine.cwd,
69
+ rawCwd: cwd,
70
+ projectRoot: machine.projectRoot,
71
+ home: machine.home,
72
+ env: runtime.env,
73
+ fs: deps.linkFs ?? NODE_LINK_FS
74
+ };
75
+ }
76
+ function profileName(args, runtime) {
77
+ try {
78
+ const auth = resolveCliAuth(args, runtime.env);
79
+ return auth.kind === "profile" ? auth.profile : undefined;
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
84
+ }
85
+ /** The links in this folder, placed with this computer's copy of the rules. */
86
+ export function linksHere(args, runtime, deps = {}) {
87
+ const profile = profileName(args, runtime);
88
+ const policy = profile ? readCliPolicy(profile) : null;
89
+ const v2 = policy?.version === 2 ? policy.autopilot : undefined;
90
+ return detectLinks(whereHere(runtime, deps), {
91
+ ...(v2 ? { flags: v2.environmentFlags, known: v2.environments } : {}),
92
+ ...(v2?.resources ? { resources: v2.resources } : {})
93
+ });
94
+ }
95
+ export const ENV_EMPTY = "No linked apps in this folder.";
96
+ /** The Environments table `init` shows for this project. */
97
+ export function envTableLines(rows) {
98
+ if (!rows.length)
99
+ return [ENV_EMPTY];
100
+ const notes = rows.filter((row) => row.note).map((row) => `${row.vendor} ${row.resource}: ${row.note}`);
101
+ return [table(rows), ...notes];
102
+ }
103
+ async function setEnvironment(args, runtime, deps) {
104
+ const [, vendor, resource, kind] = args.positionals;
105
+ if (!vendor || !resource || !kind) {
106
+ return failure("Use: passport env set <vendor> <resource> <production|staging|development>", 6, "usage");
107
+ }
108
+ if (!isEnvKind(kind))
109
+ return failure("The environment must be production, staging, or development.", 6, "usage");
110
+ // A resource found in this folder is set by its id; anything else by its name.
111
+ const wanted = resource.toLowerCase();
112
+ const found = linksHere(args, runtime, deps).find((link) => (link.vendor === vendor || vendorName(link.vendor).toLowerCase() === vendor.toLowerCase()) &&
113
+ [link.target.label, link.target.name, link.target.resourceKey].some((candidate) => candidate?.toLowerCase() === wanted));
114
+ const platform = found?.target.platform ?? platformOf(found?.vendor ?? vendor);
115
+ const key = found?.target.resourceKey ?? `name:${wanted}`;
116
+ if (!/^[a-z0-9._-]{1,40}$/.test(platform) || key.length > 200)
117
+ return failure("That resource isn't recognized.", 6, "usage");
118
+ let client = deps.api;
119
+ if (!client) {
120
+ const auth = resolveCliAuth(args, runtime.env);
121
+ if (auth.kind !== "profile") {
122
+ return failure("This needs a member profile.", 6, "member_profile_required", { hint: "Run: passport login" });
123
+ }
124
+ client = memberApi({
125
+ auth,
126
+ caller: callerFrom(args, runtime.env),
127
+ timeoutMs: timeoutMs(args),
128
+ signal: runtime.signal
129
+ });
130
+ }
131
+ const response = await client.fetchApi(`/api/my/environments/${encodeURIComponent(platform)}/${encodeURIComponent(key)}`, {
132
+ method: "PUT",
133
+ headers: { "content-type": "application/json", accept: "application/json" },
134
+ body: JSON.stringify({ kind, label: found?.target.label ?? resource }),
135
+ signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(timeoutMs(args))])
136
+ });
137
+ if (!response.ok) {
138
+ const refused = await safeApiError(response, "Passport couldn't place it.");
139
+ return failure(refused, response.status === 403 ? 5 : 1, response.status === 403 ? "forbidden" : "server");
140
+ }
141
+ await response.body?.cancel().catch(() => undefined);
142
+ const label = found?.target.label ?? resource;
143
+ const human = `${vendorName(found?.vendor ?? vendor)} ${label} is now ${ENV_LABEL[kind]} for the whole workspace.`;
144
+ return { json: { vendor, resource: label, kind }, human, essential: true };
145
+ }
146
+ export async function env(args, runtime, deps = {}) {
147
+ const action = args.positionals[0];
148
+ if (action === "set")
149
+ return setEnvironment(args, runtime, deps);
150
+ if (action !== undefined)
151
+ return failure("Use: passport env, or passport env set <vendor> <resource> <kind>.", 6, "usage");
152
+ const rows = envRows(linksHere(args, runtime, deps));
153
+ return {
154
+ json: { environments: rows, ...(value(args, "profile") ? { profile: value(args, "profile") } : {}) },
155
+ human: envTableLines(rows).join("\n")
156
+ };
157
+ }
package/dist/cliExec.d.ts CHANGED
@@ -20,6 +20,7 @@
20
20
  import { type SpawnOptions } from "node:child_process";
21
21
  import { type ParsedArgs } from "./cliArgs.js";
22
22
  import { type MemberApi } from "./cliClient.js";
23
+ import type { WhereContext } from "./envTarget.js";
23
24
  import { readCliPolicy } from "./cliPolicy.js";
24
25
  import { type CommandResult, type Runtime } from "./cliSupport.js";
25
26
  import { type ExecVendor } from "./execVendors.js";
@@ -36,6 +37,23 @@ export type ExecDependencies = {
36
37
  interactive?: boolean;
37
38
  now?: () => number;
38
39
  };
40
+ type Authorized = {
41
+ decision?: unknown;
42
+ actionId?: unknown;
43
+ explanation?: unknown;
44
+ message?: unknown;
45
+ approvalId?: unknown;
46
+ actionClass?: unknown;
47
+ credential?: {
48
+ env?: unknown;
49
+ issuance?: unknown;
50
+ label?: unknown;
51
+ expiresAt?: unknown;
52
+ };
53
+ /** Phase 4: a backup was taken right before, or couldn't be (with the reason). */
54
+ backup?: unknown;
55
+ backupNote?: unknown;
56
+ };
39
57
  /** Which vendor, or one line saying why exec won't run it. */
40
58
  export declare function execTarget(argv: readonly string[]): {
41
59
  vendor: ExecVendor;
@@ -44,12 +62,12 @@ export declare function execTarget(argv: readonly string[]): {
44
62
  refused: string;
45
63
  };
46
64
  /** The classified finding the server decides on: vendor, verb, risk, environment. */
47
- export declare function execFinding(vendor: ExecVendor, binary: string, args: readonly string[], policy: ReturnType<typeof readCliPolicy>): {
65
+ export declare function execFinding(vendor: ExecVendor, binary: string, args: readonly string[], policy: ReturnType<typeof readCliPolicy>, where?: WhereContext): {
48
66
  vendor: string;
49
67
  verb: string;
50
68
  risk: string;
51
69
  environment?: string;
52
- };
70
+ } & Record<string, string>;
53
71
  /** gh acts on `--repo owner/name`, or the folder's GitHub origin. */
54
72
  export declare function githubRepo(args: readonly string[], cwd: string): string | undefined;
55
73
  /** Only the vendor's own variables, as plain single-line strings. */
@@ -60,3 +78,6 @@ export declare function childEnvironment(base: NodeJS.ProcessEnv, credential: Re
60
78
  /** "Passport: railway redeploy changes Production. Waiting up to 120 seconds for Ramish. Approve it on your phone or in Passport." */
61
79
  export declare function waitingLine(message: string, seconds: number): string;
62
80
  export declare function exec(args: ParsedArgs, runtime: Runtime, deps?: ExecDependencies): Promise<CommandResult>;
81
+ /** One line after the run on the backup Passport took first, or couldn't. */
82
+ export declare function backupLine(decided: Authorized, exitCode: number): string | undefined;
83
+ export {};