passport-bridge 0.26.0 → 0.27.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 (42) hide show
  1. package/README.md +2 -2
  2. package/dist/blindKind.d.ts +15 -0
  3. package/dist/blindKind.js +5 -0
  4. package/dist/cliChanges.d.ts +12 -4
  5. package/dist/cliChanges.js +26 -15
  6. package/dist/cliGuardState.js +2 -2
  7. package/dist/cliHookBlind.d.ts +15 -0
  8. package/dist/cliHookBlind.js +65 -0
  9. package/dist/cliHookLocal.d.ts +7 -16
  10. package/dist/cliHookLocal.js +75 -97
  11. package/dist/cliHookLocalCode.js +7 -1
  12. package/dist/cliHookLocalFs.d.ts +15 -0
  13. package/dist/cliHookLocalFs.js +77 -0
  14. package/dist/cliHookScripts.d.ts +2 -1
  15. package/dist/cliOutput.js +2 -2
  16. package/dist/cliProjectSummary.d.ts +1 -1
  17. package/dist/cliProjectSummary.js +19 -8
  18. package/dist/cliScriptRead.d.ts +5 -4
  19. package/dist/cliScriptRead.js +3 -2
  20. package/dist/cliSeen.d.ts +24 -15
  21. package/dist/cliSeen.js +34 -16
  22. package/dist/cliSessions.js +20 -6
  23. package/dist/cliSessionsJson.d.ts +48 -0
  24. package/dist/cliSessionsJson.js +40 -10
  25. package/dist/cliSessionsRender.d.ts +4 -0
  26. package/dist/cliSessionsRender.js +42 -8
  27. package/dist/inlineCode.d.ts +35 -0
  28. package/dist/inlineCode.js +201 -0
  29. package/dist/inlineScan.d.ts +23 -0
  30. package/dist/inlineScan.js +389 -0
  31. package/dist/localCommands.d.ts +10 -3
  32. package/dist/localCommands.js +59 -37
  33. package/dist/localFiles.d.ts +38 -2
  34. package/dist/localFiles.js +453 -33
  35. package/dist/localGit.js +53 -17
  36. package/dist/localShared.d.ts +3 -0
  37. package/dist/pluginPin.d.ts +1 -1
  38. package/dist/pluginPin.js +1 -1
  39. package/dist/version.d.ts +1 -1
  40. package/dist/version.js +1 -1
  41. package/npm-shrinkwrap.json +2 -2
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -307,8 +307,8 @@ passport actions sync # propose this repository's .passport/actions.toml
307
307
 
308
308
  - `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.
309
309
  - `wait` long-polls `GET /api/my/approvals/<id>/wait` (30 s per request), after a short first look that names who decides, until a person decides or the request expires; `--timeout <s>` caps it. Agents run it as a background command and are woken when it exits. Once Passport says the request is still pending (never for one that doesn't exist or is already decided), on a terminal it prints the approval link and one live line (`Waiting for Erin · 1:32 left`); piped, `Waiting for a decision on <id> (until it expires at 14:05).` and `Open in Passport: <url>`. Ctrl-C exits 4 with `The request is still open. Keep waiting any time.` and `Run: passport wait <id>`. Approved: `Approved by Ramish (once). Run the command again.`, or `… for this session. Matching commands in this session run without asking.` (exit 0). Declined: the person's note, cleaned and labelled, `Declined by Ramish. Their note: "Use staging first"` (exit 5, cause `approval_denied`). Expired: `Expired at 14:05 with no decision. Run the command again to ask again.` (exit 5, cause `approval_expired`). Still waiting at `--timeout`: exit 4 with the same command as `next`.
310
- - `sessions` lists work items the way the Sessions page does (`GET /api/my/work-items`): a pull request or branch with every session on it rolled up, grouped by project (or, for app connections, by the apps they used). Each item has its agents, then one shape line: actions, active time, failed, confirmed Production changes, unplaced changes, asks with how they ended, blocked, data checks, undone, and the share Passport couldn't check. Notable items come first; the rest fold into `14 routine work items · 3,200 reads · nothing needed you`. `--all` lists every item, `--running` only those with a running session, and `--production-changes` prints the ledger (`GET /api/my/production-ledger`, 7 days unless `--since`): changes to confirmed Production by app and target, then the unplaced count with a link to set environments. `--project`, `--pr`, `--since` (`today`, `24h`, `7d`, `30d`, `90d`, or a date read in local time), and `--status running|ended` go to the server, which applies them to every session in the window, never to a loaded page. The CLI follows up to five pages and then links the rest. `--project <name>` on its own (no lens, `--pr`, or `--status`) opens with the web project page's summary (`GET /api/my/projects/<name>`): sessions and how many run, Environments (the repository's placement, then each platform its changes reached and how many were unplaced), the rules for the apps and scripts it uses, and its Production changes in the last 7 days, then the work list; `--json` adds it as `project` (`{project,link,sinceTs,environments:[{appKey,appName,role,label,kind,source,reached,unplaced}],rules:[{id,kind,label,decision}],moreRules,production:{total,unplaced,apps},totals}`), and a server without the page prints the list alone. A work item with several sessions links to its own page (`#projects/<name>/work?branch=`). `sessions <id>` reads one session (`GET /api/my/agent-sessions/<id>`): its title, place, agent, and active time; the web page's summary strip (actions, shipped, Production, failed, asked, not checked, undo, data checks); and its 15 latest actions with what each acted on, where it landed, and how it ended. On a terminal parts wrap only between `·` and the timeline stacks when it doesn't fit; piped output never wraps and has no color.
311
- - `changes` lists every change, delete, and irreversible action that ran on confirmed Production in the window (`GET /api/my/production-changes`), the list Sessions › Production changes shows: grouped by app, newest first, each with its time and command (and what it acted on), then the agent, the person, the pull request (else branch), Failed or Approved, and Undo available, Undone by, or Undo expired. Consecutive alike changes (same command, target, agent, person, repository, and branch) fold into one line, `git push → main ×28` with their span of times, unless one failed, was approved, or has an undo state; `--json` keeps every change. With changes from more than one repository, each line names its repository. Blocked and declined actions never reached Production and aren't listed; unplaced changes are one count with a link to set environments. `--since` takes `1h`, `6h`, `24h` (the default), `7d`, `30d`, `today`, or a date read in local time; `--until` a date; `--project`, `--pr`, `--app`, and `--agent` narrow on the server. `--env` accepts only `production` for now. When the window holds more than one read returns, it says so and links the web page. The deploy and error lanes are web-only.
310
+ - `sessions` lists work items the way the Sessions page does (`GET /api/my/work-items`): a pull request or branch with every session on it rolled up, grouped by project (or, for app connections, by the apps they used). Each item has its agents, then one shape line: actions, active time, failed, confirmed Production changes, unplaced changes, asks with how they ended, blocked, data checks, undone, and the share Passport couldn't check. Notable items come first; the rest fold into `14 routine work items · 3,200 reads · nothing needed you`. `--all` lists every item, `--running` only those with a running session, and `--production-changes` prints the ledger (`GET /api/my/production-ledger`, 7 days unless `--since`): changes to confirmed Production by app and target, then the unplaced count with a link to set environments. `--project`, `--pr`, `--since` (`today`, `24h`, `7d`, `30d`, `90d`, or a date read in local time), and `--status running|ended` go to the server, which applies them to every session in the window, never to a loaded page. The CLI follows up to five pages and then links the rest. `--project <name>` on its own (no lens, `--pr`, or `--status`) opens with the web project page's summary (`GET /api/my/projects/<name>`): sessions and how many run, Environments (the repository's placement, then each platform its changes reached and how many were unplaced), the rules for the apps and scripts it uses, and its Production changes, all over the same window as `--since` (any time without it), then the work list; `--json` adds it as `project` (`{project,link,sinceTs,environments:[{appKey,appName,role,label,kind,source,reached,unplaced}],rules:[{id,kind,label,decision}],moreRules,production:{total,unplaced,apps},totals}`), and a server without the page prints the list alone. A work item with several sessions links to its own page (`#projects/<name>/work?branch=`). Every count the server sends carries its window (`window: {since, until, label}`); the CLI prints the label after the count (`16 work items · … · Last 7 days`) and keeps its own words for an older server. `sessions <id>` reads one session (`GET /api/my/agent-sessions/<id>`): its title, place, agent, and active time; the web page's summary strip (actions, shipped, Production, failed, asked, not checked, undo, data checks); and its 15 latest actions with what each acted on, where it landed, and how it ended. On a terminal parts wrap only between `·` and the timeline stacks when it doesn't fit; piped output never wraps and has no color.
311
+ - `changes` lists every change, delete, and irreversible action that ran on confirmed Production in the window (`GET /api/my/production-changes`), the list Sessions › Production changes shows: grouped by app, newest first, each with its time and command (and what it acted on), then the agent, the person, the pull request (else branch), Failed or Approved, and Undo available, Undone by, or Undo expired. Consecutive alike changes (same command, target, agent, person, repository, and branch) fold into one line, `git push → main ×28` with their span of times, unless one failed, was approved, or has an undo state; `--json` keeps every change. With changes from more than one repository, each line names its repository. Blocked and declined actions never reached Production and aren't listed; unplaced changes are one count with a link to set environments. `--since` takes `1h`, `6h`, `24h`, `7d` (the default), `30d`, `today`, or a date read in local time; `--until` a date; `--project`, `--pr`, `--app`, and `--agent` narrow on the server. `--env` accepts only `production` for now. When the window holds more than one read returns, it says so and links the web page. The deploy and error lanes are web-only.
312
312
  - `sync` writes the allows Passport is sure of into each agent's own permission settings, so those prompts disappear offline and in Codex (`src/nativeSync.ts`). Only reads, test runners, builds and type checks, linters that only check, `git status`, `git add`, and `git commit`, checked against the person's rules. Formatters, fixing linters, `mv`/`cp`, and package scripts stay with the hook, which sees what they touch; deletes, installs, pushes, and Production never sync. Claude Code: `Bash(npm test *)` in `permissions.allow` of `~/.claude/settings.json`. Codex: `prefix_rule(pattern = ["npm", "test"], decision = "allow")` in `~/.codex/rules/passport.rules`, a file Passport owns. Cursor CLI: `Shell(npm:test*)` in `permissions.allow` of `~/.cursor/cli-config.json`. Cursor: `npm test` in `terminalAllowlist` of `~/.cursor/permissions.json`, only when that list already exists there (defining it replaces Cursor's in-app list). Entries Passport added are listed in `$PASSPORT_HOME/native-sync.json`; an entry you had before is never claimed or removed, and a file Passport can't parse exactly (JSONC) is left alone. Sync runs on `init`, `init --org`, every rules refresh, and `passport sync`; `hook uninstall`, `sync --remove`, and signing out of the last profile take the entries out.
313
313
  - `status` is one screen, like `gh auth status`, with a label per row (`You` with the name you signed in as, `Computer`, `Guard`, `Autopilot`, `Apps`, `Keys`, `Shims`, `This folder`, `Allowlists`, `CLI`); under 60 columns each label gets its own row, and piped it never wraps. `Guard` lists each agent's guard (`✓ Claude Code On`, `! Codex Not trusted`) with its fix on the line under it, the coverage line, and sends the daily guard report when due. It also adds today's speed line, `Passport adds ~20 ms per action and asked you twice today. 412 actions ran on their own.` (across your computers when the server keeps speed numbers, else `(this computer)`), and `Answered for you: N prompts today` (allows the hook gave in Claude Code and Cursor, and Codex commands Passport synced, counted only when the agent would have prompted) and which agents' allowlists are synced. Under the presets, one line per exception that lets something run your presets would ask about, in the web's words: `! 1 exception: deletes run in Production without asking, even without a backup.` Counts are appended locally (`$PASSPORT_HOME/answered/`) and sent in batches at most every five minutes as `answered: {batch, count}` on `POST /api/my/cli-activity`.
314
314
  - `actions` tells Passport what a project script does (`src/cliActions.ts`): `actions add <script> [args…] --environment <kind> --class <class>` sends the path in the repository (or `make`, `npm`, `pnpm`, `yarn` with the target), an argument glob, the repository's remote fingerprint and name, and the SHA-256 of what it runs, never its contents, to `POST /api/my/project-actions`. `--id <op_…>` resolves a Session row's **Tell Passport what this does** from this computer's scan cache. `actions sync` proposes each entry of `.passport/actions.toml`. A change, delete, or irreversible in Production applies at once; anything looser waits for an admin. The guard then decides a matching run as vendor `project` with that class and environment; it never makes a line allowed on its own, and a changed script stops matching (`projectChanged`) until it's set again. `.passport/actions.toml` entries apply locally only when they ask or block.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a blind part of a command was, for coverage (`cliSeen.ts`): interpreter
3
+ * code on the line or in a heredoc, a file run by path or given to an
4
+ * interpreter (scripts, task targets, package scripts Passport couldn't
5
+ * read), or a program Passport doesn't know. Shared by the classifier,
6
+ * script reading, and the coverage log; imports nothing.
7
+ */
8
+ export type BlindKind = "inline" | "script" | "program";
9
+ /** The blind part of a classified line: its program's name, never a path, and its kind. */
10
+ export type Blind = {
11
+ program: string;
12
+ kind: BlindKind;
13
+ };
14
+ /** A blind part written as `program\tkind` (the coverage log, the script cache); no tab: a program. */
15
+ export declare function blindOfText(text: string): Blind;
@@ -0,0 +1,5 @@
1
+ /** A blind part written as `program\tkind` (the coverage log, the script cache); no tab: a program. */
2
+ export function blindOfText(text) {
3
+ const [program = "", kind] = text.split("\t");
4
+ return { program, kind: kind === "inline" || kind === "script" ? kind : "program" };
5
+ }
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `passport changes`: what changed in Production, the list Sessions ›
3
- * Production changes shows. Every change, delete, and irreversible action
4
- * that ran on confirmed Production in the window, grouped by app, newest
5
- * first, with the agent, the person, the work item, the result, and undo.
3
+ * Production changes shows. Every Production change in the window (a change
4
+ * that ran and succeeded on Production or on a target nobody placed, by the
5
+ * server's one classifier), grouped by app, newest first, with the agent, the
6
+ * person, the work item, the result, and undo.
6
7
  *
7
- * passport changes the last 24 hours
8
+ * passport changes the last 7 days
8
9
  * passport changes --env production --since 1h
9
10
  *
10
11
  * Filters run on the server (`GET /api/my/production-changes`). `--json`
@@ -13,6 +14,7 @@
13
14
  import { type ParsedArgs } from "./cliArgs.js";
14
15
  import { type AutopilotDependencies } from "./cliMemberCall.js";
15
16
  import { type CommandResult, type Runtime } from "./cliSupport.js";
17
+ import { type WindowJson } from "./cliSessionsJson.js";
16
18
  import { type Term } from "./term.js";
17
19
  export type UndoJson = {
18
20
  state: string;
@@ -33,6 +35,8 @@ export type ChangeJson = {
33
35
  actionClass: "change" | "delete" | "irreversible";
34
36
  result: "ok" | "error";
35
37
  approved: boolean;
38
+ /** Its target nobody placed: counted as Production until someone does. */
39
+ unplaced: boolean;
36
40
  sessionId: string | null;
37
41
  project: string | null;
38
42
  branch: string | null;
@@ -51,7 +55,11 @@ export type ChangesJson = {
51
55
  untilTs: number | null;
52
56
  total: number;
53
57
  unplaced: number;
58
+ /** False from a server that counted unplaced changes apart from `total`. */
59
+ unplacedIncluded: boolean;
54
60
  complete: boolean;
61
+ /** The span `total` covers; null from older servers. */
62
+ window: WindowJson | null;
55
63
  apps: Array<{
56
64
  vendor: string;
57
65
  appName: string;
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * `passport changes`: what changed in Production, the list Sessions ›
3
- * Production changes shows. Every change, delete, and irreversible action
4
- * that ran on confirmed Production in the window, grouped by app, newest
5
- * first, with the agent, the person, the work item, the result, and undo.
3
+ * Production changes shows. Every Production change in the window (a change
4
+ * that ran and succeeded on Production or on a target nobody placed, by the
5
+ * server's one classifier), grouped by app, newest first, with the agent, the
6
+ * person, the work item, the result, and undo.
6
7
  *
7
- * passport changes the last 24 hours
8
+ * passport changes the last 7 days
8
9
  * passport changes --env production --since 1h
9
10
  *
10
11
  * Filters run on the server (`GET /api/my/production-changes`). `--json`
@@ -13,13 +14,13 @@
13
14
  import { value } from "./cliArgs.js";
14
15
  import { api, json } from "./cliMemberCall.js";
15
16
  import { failure, timeoutMs } from "./cliSupport.js";
16
- import { appName, clientName, count, list, oneOf, record, text, time } from "./cliSessionsJson.js";
17
+ import { appName, clientName, count, list, oneOf, record, text, time, windowOf } from "./cliSessionsJson.js";
17
18
  import { countOf } from "./plural.js";
18
19
  import { joinParts, mark, visibleLength, wrap, termOf } from "./term.js";
19
20
  import { hashLink } from "./webLinks.js";
20
21
  const DATE = /^\d{4}-\d{2}-\d{2}$/;
21
22
  const RANGES = ["1h", "6h", "24h", "7d", "30d", "today"];
22
- const DEFAULT_SINCE = "24h";
23
+ const DEFAULT_SINCE = "7d";
23
24
  const WINDOW_WORDS = {
24
25
  "1h": "last hour",
25
26
  "6h": "last 6 hours",
@@ -138,6 +139,7 @@ function changeOf(raw) {
138
139
  actionClass: oneOf(entry.actionClass, ["change", "delete", "irreversible"]) ?? "change",
139
140
  result: entry.result === "error" ? "error" : "ok",
140
141
  approved: entry.approved === true,
142
+ unplaced: entry.unplaced === true,
141
143
  sessionId: text(entry.sessionId, 128) ?? null,
142
144
  project: text(work.project, 200) ?? null,
143
145
  branch: text(work.branch, 200) ?? null,
@@ -180,7 +182,9 @@ export function changesOf(raw) {
180
182
  untilTs: time(page.untilTs),
181
183
  total: Math.max(count(page.total), changes.length),
182
184
  unplaced: count(page.unplaced),
185
+ unplacedIncluded: page.unplacedIncluded === true,
183
186
  complete: page.complete !== false,
187
+ window: windowOf(page.window),
184
188
  apps
185
189
  };
186
190
  }
@@ -228,6 +232,8 @@ export function changeParts(change, projects = false) {
228
232
  parts.push(change.branch);
229
233
  if (change.result === "error")
230
234
  parts.push("Failed");
235
+ if (change.unplaced)
236
+ parts.push("Unplaced");
231
237
  if (change.approved)
232
238
  parts.push("Approved");
233
239
  const undo = undoPart(change.undo);
@@ -268,18 +274,22 @@ export function foldChanges(changes) {
268
274
  }
269
275
  return runs;
270
276
  }
271
- function windowWord(since, sinceTs, now) {
272
- return WINDOW_WORDS[since] ?? (sinceTs ? `since ${changeTime(sinceTs, now)}` : `since ${since}`);
277
+ /** The server's label for the window it counted; an older server's, worded here. */
278
+ function windowWord(page, since, now) {
279
+ if (page.window)
280
+ return page.window.label;
281
+ return WINDOW_WORDS[since] ?? (page.sinceTs ? `since ${changeTime(page.sinceTs, now)}` : `since ${since}`);
273
282
  }
274
283
  export function renderChanges(page, term, now, since, links) {
275
284
  const arrow = term.unicode ? "→" : "->";
276
- const lines = joinParts([
277
- "Production changes",
278
- windowWord(since, page.sinceTs, now),
279
- `${countOf(page.total, "change")} on confirmed Production`
280
- ], term.width);
285
+ // Since the count shape, unplaced changes are among the total and listed;
286
+ // an older server listed confirmed Production only.
287
+ const where = page.unplacedIncluded ? "on Production" : "on confirmed Production";
288
+ const lines = joinParts(["Production changes", windowWord(page, since, now), `${countOf(page.total, "change")} ${where}`], term.width);
281
289
  if (!page.apps.length)
282
- lines.push("", ...wrap("Nothing your agents ran changed a target you placed in Production in this window.", term.width));
290
+ lines.push("", ...wrap(page.unplacedIncluded
291
+ ? "Nothing your agents ran changed Production in this window."
292
+ : "Nothing your agents ran changed a target you placed in Production in this window.", term.width));
283
293
  const projects = new Set(page.apps.flatMap((app) => app.changes.map((change) => change.project)).filter(Boolean)).size > 1;
284
294
  const times = term.unicode ? "×" : "x";
285
295
  for (const app of page.apps) {
@@ -301,7 +311,8 @@ export function renderChanges(page, term, now, since, links) {
301
311
  lines.push(`See all: ${links.more}`);
302
312
  }
303
313
  if (page.unplaced) {
304
- lines.push("", ...wrap(`${countOf(page.unplaced, "unplaced action")}, counted as Production until you place them.`, term.width));
314
+ const among = page.unplacedIncluded ? " among them" : "";
315
+ lines.push("", ...wrap(`${countOf(page.unplaced, "unplaced action")}${among}, counted as Production until you place them.`, term.width));
305
316
  if (links.environments)
306
317
  lines.push(`Set environments: ${links.environments}`);
307
318
  }
@@ -87,8 +87,8 @@ export function problemFix(kind, client) {
87
87
  return {
88
88
  text: "Move it back into Passport.",
89
89
  command: "passport keys move",
90
- link: "#apps",
91
- docs: `${DOCS_BASE}/member/cli-hook#keys-back-on-a-computer`
90
+ link: "#settings/keys",
91
+ docs: `${DOCS_BASE}/member/cli-hook#keys-in-passport`
92
92
  };
93
93
  }
94
94
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a blind part of a command was, for coverage: the program that ran it
3
+ * (a plain name, never a path) and its kind, so Rules › Project scripts can
4
+ * tell inline code from a project script from a program Passport doesn't know.
5
+ */
6
+ import type { BlindKind } from "./blindKind.js";
7
+ import type { ShellWord } from "./localCommands.js";
8
+ /** The program a part ran, by name. A file run by path (`./x.sh`, `~/bin/tool`,
9
+ * `$HOME/bin/tool`, `node_modules/.bin/tsc`) is "script". */
10
+ export declare function programOf(argv: string[]): string;
11
+ /** A program run from the home folder by `$HOME/…`: read like `~/…`, so its place is known. */
12
+ export declare function homeProgram<W extends ShellWord>(words: W[]): W[];
13
+ /** Script: a file run by path or given to an interpreter, a task target, a package
14
+ * script Passport couldn't read. Program: anything else it doesn't know. */
15
+ export declare function blindKind(program: string, argv: string[]): BlindKind;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What a blind part of a command was, for coverage: the program that ran it
3
+ * (a plain name, never a path) and its kind, so Rules › Project scripts can
4
+ * tell inline code from a project script from a program Passport doesn't know.
5
+ */
6
+ import { normalizeArgv } from "./cliHookParse.js";
7
+ const HOME_PATH = /^(?:\$HOME|\$\{HOME\})(?=\/|$)/;
8
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
9
+ /** The program a part ran, by name. A file run by path (`./x.sh`, `~/bin/tool`,
10
+ * `$HOME/bin/tool`, `node_modules/.bin/tsc`) is "script". */
11
+ export function programOf(argv) {
12
+ const normalized = normalizeArgv(argv);
13
+ if (normalized.via.includes("absolute-path"))
14
+ return "script";
15
+ const first = argv[argv.length - normalized.argv.length] ?? "";
16
+ return HOME_PATH.test(first) || first.startsWith("~") ? "script" : (normalized.argv[0] ?? "");
17
+ }
18
+ /** A program run from the home folder by `$HOME/…`: read like `~/…`, so its place is known. */
19
+ export function homeProgram(words) {
20
+ const index = words.findIndex((word) => !ASSIGNMENT.test(word.text));
21
+ const head = words[index];
22
+ if (!head?.expands || !HOME_PATH.test(head.text))
23
+ return words;
24
+ const rest = head.text.replace(HOME_PATH, "");
25
+ if (/[$`*?[]/.test(rest))
26
+ return words;
27
+ const copy = [...words];
28
+ copy[index] = { text: `~${rest}`, tilde: true };
29
+ return copy;
30
+ }
31
+ const RUNNERS = new Set([
32
+ "node",
33
+ "nodejs",
34
+ "tsx",
35
+ "ts-node",
36
+ "bun",
37
+ "deno",
38
+ "python",
39
+ "python2",
40
+ "python3",
41
+ "ruby",
42
+ "perl",
43
+ "bash",
44
+ "sh",
45
+ "zsh",
46
+ "dash",
47
+ "ksh",
48
+ "fish",
49
+ "php",
50
+ "osascript"
51
+ ]);
52
+ const TASK_RUNNERS = new Set(["make", "just", "task", "source", "."]);
53
+ const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
54
+ /** Script: a file run by path or given to an interpreter, a task target, a package
55
+ * script Passport couldn't read. Program: anything else it doesn't know. */
56
+ export function blindKind(program, argv) {
57
+ if (program === "script" || TASK_RUNNERS.has(program))
58
+ return "script";
59
+ const rest = normalizeArgv(argv).argv.slice(1);
60
+ if (RUNNERS.has(program) && rest.some((word) => !word.startsWith("-")))
61
+ return "script";
62
+ if (PACKAGE_MANAGERS.has(program) && /^(run|run-script)$/.test(rest.find((word) => !word.startsWith("-")) ?? ""))
63
+ return "script";
64
+ return "program";
65
+ }
@@ -15,21 +15,12 @@
15
15
  * applies. Asks and blocks still come from whatever parts were understood.
16
16
  */
17
17
  import { type CliFinding } from "./cliHookClassify.js";
18
- import { type FileStat, type ScriptFile, type ScriptReader } from "./cliScriptRead.js";
18
+ import type { Blind } from "./blindKind.js";
19
+ import type { ScriptReader } from "./cliScriptRead.js";
20
+ import { type LocalFs } from "./cliHookLocalFs.js";
19
21
  import type { DecidedFinding } from "./cliHookGuard.js";
20
22
  import { type LocalAction, type Place, type ShellWord } from "./localCommands.js";
21
- /** What the hook can read from the machine. Injected so tests never touch it. */
22
- export type LocalFs = {
23
- /** The canonical path, or null when it doesn't exist. */
24
- realpath(path: string): string | null;
25
- /** A small text file, or null. */
26
- readText(path: string): string | null;
27
- isDirectory(path: string): boolean;
28
- isFile(path: string): boolean;
29
- /** A script up to 256 KB with its time and size (script reading), or null. */
30
- readScript?(path: string): ScriptFile | null;
31
- statFile?(path: string): FileStat | null;
32
- };
23
+ export { NODE_FS, type LocalFs } from "./cliHookLocalFs.js";
33
24
  export type LocalMachine = {
34
25
  /** The folder the agent's command starts in, canonical; null when unknown. */
35
26
  cwd: string | null;
@@ -47,7 +38,6 @@ export type LocalMachine = {
47
38
  /** Read the project's own scripts (`cliScriptRead.ts`). Absent: scripts stay unread. */
48
39
  scripts?: ScriptReader;
49
40
  };
50
- export declare const NODE_FS: LocalFs;
51
41
  /** Canonical form of a path that may not exist yet: resolve the deepest
52
42
  * existing ancestor (following symlinks) and keep the rest as written. */
53
43
  export declare function canonical(path: string, fs: LocalFs): string;
@@ -79,8 +69,9 @@ export type LineResult = {
79
69
  /** Every part understood: the only lines Passport may allow. */
80
70
  complete: boolean;
81
71
  /** A part Passport couldn't tell anything about (an unknown program, a
82
- * one-liner): the program that ran it, for coverage's Blind count. */
83
- blind?: string;
72
+ * one-liner it couldn't read): the program that ran it and its kind, for
73
+ * coverage's Blind count. */
74
+ blind?: Blind;
84
75
  };
85
76
  /** A local action as a finding the guard and reports understand. */
86
77
  export declare function localFinding(action: LocalAction): CliFinding;
@@ -14,91 +14,19 @@
14
14
  * leaves the line incomplete, which means no allow: the agent's own prompt
15
15
  * applies. Asks and blocks still come from whatever parts were understood.
16
16
  */
17
- import { closeSync, fstatSync, lstatSync, openSync, readFileSync, readSync, realpathSync, statSync } from "node:fs";
18
17
  import { homedir, tmpdir } from "node:os";
19
18
  import { posix } from "node:path";
20
19
  import { classifyArgv, classifyNestedText } from "./cliHookClassify.js";
21
20
  import { heredocBodies, projectCode } from "./cliHookLocalCode.js";
22
- import { SCRIPT_MAX_BYTES } from "./cliScriptRead.js";
21
+ import { blindKind, homeProgram, programOf } from "./cliHookBlind.js";
22
+ import { inlineCode } from "./inlineCode.js";
23
+ import { NODE_FS } from "./cliHookLocalFs.js";
23
24
  import { scriptReading } from "./cliHookScripts.js";
24
- import { INTERPRETERS, normalizeArgv, splitCommands } from "./cliHookParse.js";
25
+ import { INTERPRETERS, splitCommands } from "./cliHookParse.js";
25
26
  import { VENDORS } from "./cliHookVendors.js";
26
27
  import { databasePrefix } from "./envDatabase.js";
27
28
  import { classifyLocalCommand } from "./localCommands.js";
28
- const MAX_TEXT = 4096;
29
- export const NODE_FS = {
30
- realpath(path) {
31
- try {
32
- return realpathSync.native(path);
33
- }
34
- catch {
35
- return null;
36
- }
37
- },
38
- readText(path) {
39
- try {
40
- if (statSync(path).size > MAX_TEXT)
41
- return null;
42
- return readFileSync(path, "utf8");
43
- }
44
- catch {
45
- return null;
46
- }
47
- },
48
- isDirectory(path) {
49
- try {
50
- return statSync(path).isDirectory();
51
- }
52
- catch {
53
- return false;
54
- }
55
- },
56
- isFile(path) {
57
- try {
58
- return lstatSync(path).isFile() || statSync(path).isFile();
59
- }
60
- catch {
61
- return false;
62
- }
63
- },
64
- readScript(path) {
65
- let descriptor;
66
- try {
67
- descriptor = openSync(path, "r");
68
- const stat = fstatSync(descriptor);
69
- if (!stat.isFile() || stat.size > SCRIPT_MAX_BYTES)
70
- return null;
71
- const buffer = Buffer.alloc(stat.size);
72
- let offset = 0;
73
- while (offset < stat.size) {
74
- const read = readSync(descriptor, buffer, offset, stat.size - offset, offset);
75
- if (read <= 0)
76
- break;
77
- offset += read;
78
- }
79
- // Binary files aren't scripts.
80
- if (buffer.subarray(0, offset).includes(0))
81
- return null;
82
- return { text: buffer.toString("utf8", 0, offset), mtimeMs: stat.mtimeMs, size: stat.size };
83
- }
84
- catch {
85
- return null;
86
- }
87
- finally {
88
- if (descriptor !== undefined)
89
- closeSync(descriptor);
90
- }
91
- },
92
- statFile(path) {
93
- try {
94
- const stat = statSync(path);
95
- return stat.isFile() ? { mtimeMs: stat.mtimeMs, size: stat.size } : null;
96
- }
97
- catch {
98
- return null;
99
- }
100
- }
101
- };
29
+ export { NODE_FS } from "./cliHookLocalFs.js";
102
30
  /** Home-relative paths whose contents are keys, tokens, or an agent's own settings. */
103
31
  const SENSITIVE_IN_HOME = [
104
32
  ".ssh",
@@ -375,16 +303,11 @@ export function localFinding(action) {
375
303
  }
376
304
  };
377
305
  }
378
- /** The program a part ran, by name. A path is never sent: a file run by path is "script". */
379
- function programOf(argv) {
380
- const normalized = normalizeArgv(argv);
381
- return normalized.via.includes("absolute-path") ? "script" : (normalized.argv[0] ?? "");
382
- }
383
306
  function isVendor(program) {
384
307
  return Object.hasOwn(VENDORS, program);
385
308
  }
386
309
  /** Interpreter flags whose code is on the line itself: a one-liner. */
387
- const INLINE_CODE = /^(-e|-p|-c|--eval|--print)$/;
310
+ const INLINE_CODE = /^(-e|-E|-p|-c|--eval|--print)$/;
388
311
  function contextAt(cwd, machine) {
389
312
  const here = cwd ? placeOfPath(cwd, machine) : "unknown";
390
313
  const branches = cwd && (here === "project" || here === "project-root") ? gitBranches(cwd, machine.fs) : null;
@@ -396,9 +319,21 @@ function contextAt(cwd, machine) {
396
319
  },
397
320
  isVendor,
398
321
  currentBranch: branches?.current ?? null,
399
- defaultBranch: branches?.defaultBranch ?? null
322
+ defaultBranch: branches?.defaultBranch ?? null,
323
+ sameRepository: (word) => {
324
+ const path = word ? resolveWord(word, cwd, machine) : cwd;
325
+ return path !== null && sharesRepository(path, machine);
326
+ }
400
327
  };
401
328
  }
329
+ /** `path` is in a checkout of the project's repository: the same common git folder. */
330
+ function sharesRepository(path, machine) {
331
+ if (!machine.projectRoot)
332
+ return false;
333
+ const there = gitLayout(path, machine.fs);
334
+ const ours = there && gitLayout(machine.projectRoot, machine.fs);
335
+ return Boolean(ours && canonical(there.commonDir, machine.fs) === canonical(ours.commonDir, machine.fs));
336
+ }
402
337
  /** Redirections: writes are changes where they land; reads of keys are no decision. */
403
338
  function redirections(shape, cwd, machine, walk) {
404
339
  for (const redirect of shape.redirects) {
@@ -443,15 +378,39 @@ function nextDirectory(target, cwd, machine) {
443
378
  return null;
444
379
  return machine.fs.isDirectory(path) ? path : null;
445
380
  }
446
- function vendorFindings(shape, outcome, walk, depth, cwd) {
381
+ /** Interpreter code on the line or in a heredoc (`inlineCode.ts`): true when it only reads. */
382
+ function inlineRead(shape, cwd, machine, heredocs, walk) {
383
+ const words = shape.words;
384
+ const key = posix.basename(words.find((word) => !/^\w+=/.test(word.text))?.text ?? "");
385
+ const body = shape.heredoc ? heredocs.bodies.get(key) : undefined;
386
+ const ctx = contextAt(cwd, machine);
387
+ const inline = inlineCode(words, body, {
388
+ ctx,
389
+ placePath: (path) => ctx.place({ text: path, ...(path.startsWith("~") ? { tilde: true } : {}) }),
390
+ shadowed: (module) => cwd !== null &&
391
+ (machine.fs.isFile(posix.join(cwd, `${module}.py`)) || machine.fs.isDirectory(posix.join(cwd, module))),
392
+ quotedHeredoc: heredocs.quoted
393
+ });
394
+ if (!inline || !("read" in inline))
395
+ return inline;
396
+ walk.findings.push(localFinding(inline.read));
397
+ if (body !== undefined)
398
+ heredocs.read.add(key);
399
+ return true;
400
+ }
401
+ function vendorFindings(shape, outcome, walk, at) {
402
+ const { depth, cwd } = at;
447
403
  const argv = shape.words.map((word) => word.text);
404
+ const inline = outcome.kind === "vendor" ? null : inlineRead(shape, cwd, at.machine, at.heredocs, walk);
405
+ if (inline === true)
406
+ return;
448
407
  // Where it runs, for folder links; database variables set in front of it.
449
408
  const prefix = databasePrefix(argv);
450
- const at = { cwd, ...(prefix ? { prefix } : {}) };
409
+ const where = { cwd, ...(prefix ? { prefix } : {}) };
451
410
  // Unrecognized here: keep only what the vendor map governs or can't see into.
452
411
  const found = classifyArgv(argv, [], depth)
453
412
  .filter((finding) => outcome.kind === "vendor" || (finding.risk !== "local" && finding.risk !== "http"))
454
- .map((finding) => ({ ...finding, at }));
413
+ .map((finding) => ({ ...finding, at: where }));
455
414
  const push = outcome.kind === "vendor" ? outcome.push : undefined;
456
415
  const findings = push
457
416
  ? found.map((finding) => (finding.vendor === "git" ? { ...finding, pushEnvironment: push } : finding))
@@ -459,11 +418,14 @@ function vendorFindings(shape, outcome, walk, depth, cwd) {
459
418
  walk.findings.push(...findings);
460
419
  if (outcome.kind !== "vendor") {
461
420
  walk.complete = false;
462
- // Blind: nothing Passport knows ran here, or code given on the line itself.
421
+ // Blind: nothing Passport knows ran here, or code it couldn't read.
463
422
  const program = programOf(argv);
464
- const oneLiner = INTERPRETERS.has(program) && argv.some((word) => INLINE_CODE.test(word));
465
- if (oneLiner || findings.every((finding) => finding.risk === "unknown"))
466
- walk.blind ??= program;
423
+ const code = inline !== null || (INTERPRETERS.has(program) && (shape.heredoc || argv.some((word) => INLINE_CODE.test(word))));
424
+ if (code || findings.every((finding) => finding.risk === "unknown")) {
425
+ // A bare assignment that changes what runs (`PATH=…`) is the shell's own.
426
+ const name = program || "export";
427
+ walk.blind ??= { program: inline?.program ?? name, kind: code ? "inline" : blindKind(name, argv) };
428
+ }
467
429
  return;
468
430
  }
469
431
  // A vendor part is understood when it is one confident, plain invocation.
@@ -517,11 +479,18 @@ export function classifyLine(command, machine, depth = 0) {
517
479
  if (depth > 4)
518
480
  return { findings: [], complete: false };
519
481
  const { shapes, nested, flags } = splitCommands(command);
520
- const heredocs = heredocBodies(nested);
521
- if (flags.braces || flags.processSubstitution || flags.heredoc || nested.length)
482
+ const bodies = heredocBodies(nested);
483
+ const heredocs = {
484
+ // Two bodies for one program can't be told apart: neither is read as code.
485
+ bodies: new Map([...bodies].filter(([key]) => nested.filter((sub) => heredocKey(sub) === key).length === 1)),
486
+ read: new Set(),
487
+ quoted: !/<<-?\s*[^\s'"<]/.test(command.replace(/<<</g, " "))
488
+ };
489
+ if (flags.braces || flags.processSubstitution || nested.some((sub) => sub.kind !== "heredoc"))
522
490
  walk.complete = false;
523
491
  const cwdAt = [machine.cwd];
524
492
  let previous = null;
493
+ let heredocShapes = 0;
525
494
  for (let index = 0; index < shapes.length; index++) {
526
495
  const shape = shapes[index];
527
496
  // Entering a subshell starts from the folder outside it; leaving one forgets its cd.
@@ -534,10 +503,11 @@ export function classifyLine(command, machine, depth = 0) {
534
503
  const cwd = cwdAt[shape.depth] ?? null;
535
504
  previous = shape;
536
505
  if (shape.heredoc)
537
- walk.complete = false;
506
+ heredocShapes++;
538
507
  redirections(shape, cwd, machine, walk);
539
508
  if (!shape.words.length)
540
509
  continue;
510
+ shape.words = homeProgram(shape.words);
541
511
  const outcome = classifyLocalCommand(shape.words, contextAt(cwd, machine));
542
512
  if (outcome.kind === "local") {
543
513
  walk.findings.push(...outcome.actions.map(localFinding));
@@ -557,13 +527,21 @@ export function classifyLine(command, machine, depth = 0) {
557
527
  cwdAt[shape.depth] = nextDirectory(outcome.target, cwd, machine);
558
528
  continue;
559
529
  }
560
- if (outcome.kind === "unknown" && ownCode(shape, { cwd, depth, heredocs }, machine, walk))
530
+ if (outcome.kind === "unknown" && ownCode(shape, { cwd, depth, heredocs: bodies }, machine, walk))
561
531
  continue;
562
- vendorFindings(shape, outcome, walk, depth, cwd);
532
+ vendorFindings(shape, outcome, walk, { depth, cwd, machine, heredocs });
563
533
  }
564
- nestedInto(nested, machine, depth, walk);
534
+ // A heredoc is hidden text unless inline code read it as a read.
535
+ const readBodies = nested.filter((sub) => sub.kind === "heredoc" && heredocs.read.has(heredocKey(sub)));
536
+ const heredocCount = nested.filter((sub) => sub.kind === "heredoc").length;
537
+ if ((flags.heredoc || heredocShapes) && (heredocCount > readBodies.length || heredocShapes > readBodies.length))
538
+ walk.complete = false;
539
+ nestedInto(nested.filter((sub) => !readBodies.includes(sub)), machine, depth, walk);
565
540
  return walk;
566
541
  }
542
+ function heredocKey(sub) {
543
+ return sub.kind === "heredoc" && sub.target ? posix.basename(sub.target) : "";
544
+ }
567
545
  /** Substitutions and heredocs: their vendor findings, and a shell's local ones. */
568
546
  function nestedInto(nested, machine, depth, walk) {
569
547
  for (const sub of nested) {
@@ -95,7 +95,7 @@ function shellLine(words) {
95
95
  function scriptOperand(words) {
96
96
  for (let index = 1; index < words.length; index++) {
97
97
  const word = words[index];
98
- if (INLINE.test(word.text))
98
+ if (INLINE.test(word.text) || bundledCode(words[0].text, word.text))
99
99
  return null;
100
100
  if (word.text === "run" && (words[0].text === "deno" || words[0].text === "bun"))
101
101
  continue;
@@ -108,6 +108,12 @@ function scriptOperand(words) {
108
108
  }
109
109
  return null;
110
110
  }
111
+ /** Code given in a flag bundle: `perl -ne`, `ruby -pe`, `python3 -Ic`. */
112
+ function bundledCode(program, flag) {
113
+ if (program === "perl" || program === "ruby")
114
+ return /^-[a-zA-Z0-9]*[eE]/.test(flag);
115
+ return program.startsWith("python") && /^-[a-zA-Z]*c/.test(flag);
116
+ }
111
117
  function runScript(program) {
112
118
  return {
113
119
  vendor: program,
@@ -0,0 +1,15 @@
1
+ /** The hook's view of this computer's files (`cliHookLocal.ts`): injected so tests never touch them. */
2
+ import { type FileStat, type ScriptFile } from "./cliScriptRead.js";
3
+ /** What the hook can read from the machine. Injected so tests never touch it. */
4
+ export type LocalFs = {
5
+ /** The canonical path, or null when it doesn't exist. */
6
+ realpath(path: string): string | null;
7
+ /** A small text file, or null. */
8
+ readText(path: string): string | null;
9
+ isDirectory(path: string): boolean;
10
+ isFile(path: string): boolean;
11
+ /** A script up to 256 KB with its time and size (script reading), or null. */
12
+ readScript?(path: string): ScriptFile | null;
13
+ statFile?(path: string): FileStat | null;
14
+ };
15
+ export declare const NODE_FS: LocalFs;