@runeditrun/rer 0.2.31 → 0.2.32

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 (49) hide show
  1. package/README.md +94 -0
  2. package/cli/README.md +32 -0
  3. package/cli/business/api.mjs +61 -0
  4. package/cli/business/command.mjs +44 -20
  5. package/cli/business/config-policy.mjs +25 -0
  6. package/cli/business/connect.mjs +50 -0
  7. package/cli/business/discovery-task.mjs +180 -0
  8. package/cli/business/files.mjs +25 -0
  9. package/cli/business/keychain.mjs +113 -0
  10. package/cli/business/lease.mjs +68 -0
  11. package/cli/business/local-commands.mjs +82 -0
  12. package/cli/business/outbound.mjs +29 -0
  13. package/cli/business/parsers-syntax.mjs +3 -1
  14. package/cli/business/parsers.mjs +9 -3
  15. package/cli/business/permissions.mjs +143 -0
  16. package/cli/business/policy.mjs +7 -1
  17. package/cli/business/progress.mjs +18 -0
  18. package/cli/business/prompts.mjs +12 -0
  19. package/cli/business/questions.mjs +98 -0
  20. package/cli/business/repository.mjs +17 -0
  21. package/cli/business/scan-command.mjs +27 -0
  22. package/cli/business/scan.mjs +42 -35
  23. package/cli/business/service.mjs +152 -0
  24. package/cli/business/state.mjs +46 -0
  25. package/cli/business/supervisor.mjs +92 -0
  26. package/cli/business/vendors/README.md +101 -0
  27. package/cli/business/vendors/calendly.mjs +80 -0
  28. package/cli/business/vendors/common.mjs +103 -0
  29. package/cli/business/vendors/index.mjs +75 -0
  30. package/cli/business/vendors/pagerduty.mjs +70 -0
  31. package/cli/business/vendors/sentry.mjs +84 -0
  32. package/cli/business/vendors/uptimerobot.mjs +20 -0
  33. package/cli/deploy-command.mjs +3 -2
  34. package/cli/deploy-inputs.mjs +9 -0
  35. package/cli/deploy.mjs +3 -2
  36. package/global/CHANGELOG.md +13 -0
  37. package/global/README.md +94 -0
  38. package/global/cli/describe.mjs +20 -0
  39. package/global/cli/install.mjs +3 -3
  40. package/global/cli/repo-command.mjs +53 -0
  41. package/global/cli/repository-contract.mjs +7 -0
  42. package/global/cli/repository.mjs +84 -0
  43. package/global/launch/prepare.mjs +9 -6
  44. package/global/main.mjs +22 -2
  45. package/install.sh +7 -0
  46. package/modules/deploy-kit/owner-cli.mjs +5 -2
  47. package/modules/deploy-kit/owner.mjs +6 -4
  48. package/modules/deploy-kit/public-origin.mjs +17 -0
  49. package/package.json +1 -1
package/README.md CHANGED
@@ -6,6 +6,24 @@ checkout always gets the behaviour it was built and tested with.
6
6
 
7
7
  ## Install
8
8
 
9
+ Start a seed from an empty folder with one command:
10
+
11
+ ```sh
12
+ npx -y @runeditrun/rer dev just-every/run-inkwell
13
+ curl -fsSL https://runeditrun.com/install.sh | sh -s -- dev just-every/run-inkwell
14
+ ```
15
+
16
+ Both install the user CLI, clone into `./run-inkwell`, install dependencies, set
17
+ up a local owner and start the app. Open the printed `RER_OPEN` link to sign in.
18
+ Use `setup <repo>` to stop after setup, or `install <repo>` to stop after
19
+ dependency installation; each prints the next command. The repo can be
20
+ `<owner>/<repo>`, a GitHub HTTPS URL (with or without `.git`), or a git URL.
21
+ `--dir DIR` chooses another folder. An existing clone with the same origin is
22
+ reused; any other non-empty folder is refused. Inside a checkout, the commands
23
+ without a repository work as before. Dev follows the usual terminal behaviour:
24
+ Ctrl-C stops a foreground app; without a terminal it returns once ready and
25
+ leaves the app running. The restart command includes `cd` into the checkout.
26
+
9
27
  Install `rer` with one of these commands:
10
28
 
11
29
  ```sh
@@ -306,9 +324,85 @@ document: `{schema: "rer-business-signals/1", source: "local", signals: [...],
306
324
  withheld: N}`. Signals identify package, environment, CI, infrastructure and
307
325
  configuration names with a relative `locator`, repository basename `repo`,
308
326
  `class` (`live-use` or `trace`) and `observedAt`.
327
+ Identical `(kind, value, repo, class)` signals are emitted once with an occurrence
328
+ `count` and the first matching `locator`. `secret-file` signals remain separate
329
+ for each path, preserving each file's size and modification time.
330
+
331
+ Config keys come only from JSON (including JSONC), YAML and TOML files in
332
+ configuration directories or with known config filenames.
333
+ Data in tests, fixtures, locales, translations, samples and exports, along with
334
+ lockfiles and generated output, contributes no config keys. The document's
335
+ `configKeyLimit` declares the maximum distinct key paths per file (currently
336
+ 200). JavaScript and TypeScript config files are not read or parsed;
337
+ dependencies still come from manifests.
309
338
 
310
339
  Only names leave the scanner. Secret files are never opened and contribute
311
340
  `secret-file` metadata (filename, path, size and modification time).
312
341
  Sensitive-looking outbound names are dropped and counted in `withheld`.
313
342
  Symlinks, generated outputs and dependency trees are skipped; unsupported
314
343
  formats and syntax may yield no signals.
344
+
345
+ ## Business device commands
346
+
347
+ `rer business connect --code ABCD-1234 [--origin https://app.runeditrun.com]`
348
+ redeems a browser-created code, prints a six-digit confirmation number and waits
349
+ for approval in the browser that created it. Device credentials stay in macOS
350
+ Keychain or Linux Secret Service. A missing or locked Secret Service refuses;
351
+ there is no plaintext credential store. Linux needs `secret-tool` and an
352
+ unlocked desktop Secret Service session.
353
+
354
+ In a terminal, connect asks separately before adding Claude Code user Read deny
355
+ rules, allowing export-scoped macOS wake prevention, and installing a launchd
356
+ or systemd user service. Only the exact answer `yes` opts in. Noninteractive
357
+ connect pairs but leaves those optional changes off. Background services use
358
+ absolute Node and CLI paths. No model process is started.
359
+
360
+ `rer business vendor-key add sentry` requires hidden credential entry in a
361
+ terminal, stores it in the OS keychain and prints only `sentry:read`.
362
+ `remove` deletes it. The same commands support `uptimerobot`, `pagerduty` and
363
+ `calendly`. Never put a key in command arguments, chat or a URL.
364
+
365
+ `rer business next` returns one locally templated classification or owner link,
366
+ or `Nothing yet`, within 60 seconds. It never reflects server instructions or
367
+ raw evidence. Owner items cannot be answered from this CLI.
368
+ `rer business answer ID VENDOR uses|sells|both|product-dependency [CONFIDENCE]`
369
+ submits a task-scoped classification through MCP. Choose a vendor ID from the
370
+ question's displayed answer schema, or `none`; the suggested vendor can be
371
+ corrected. Confidence is a number from 0 to 1, defaulting to 1. The completion
372
+ sends exactly `{vendor_id, usage, confidence}`. Free text is refused locally.
373
+ The owner confirms the inventory in the browser.
374
+ `rer business token` emits an MCP Authorization header object for direct use as
375
+ a headers helper. That output is a short-lived credential: connect it directly
376
+ to the MCP client and do not paste it into an agent transcript.
377
+
378
+ `rer business status` shows local pairing, service state and progress without
379
+ printing checkpoints or vendor data. `rer business disconnect` removes the
380
+ service, device and vendor credentials, state and introduced Claude rules,
381
+ preserving preexisting settings and unrelated edits. Revocation in the browser
382
+ removes remote authority; disconnect removes the local installation's additions.
383
+
384
+ `rer business run` performs consented `discover.local` tasks through claims,
385
+ short-lived task bearers, quota-bound uploads, 60-second heartbeats and server
386
+ completion checks. Only the browser consent's paths are scanned. Names-only
387
+ snapshots and page boundaries are saved privately so a killed supervisor can
388
+ resume from its server checkpoint without rescanning a changed tree. Snapshots
389
+ are removed after completion. A missing snapshot for an acknowledged page is
390
+ an explicit error. Revocation stops the supervisor on its next 401.
391
+
392
+ **Remaining export blockers:** grants for linked, configured targets now resolve
393
+ to an HTTPS `/api/rer/import/uploads` destination with a 2 MiB quota. They declare
394
+ `upload_authorization: seed_import_grant_required` but supply no signed seed
395
+ import authority. Vendor task inputs, adapter resume checkpoints and the chunk
396
+ assembly/upload contract are also absent. The CLI releases these tasks before
397
+ reading a vendor key; background mode parks them, and `run --once` reports the
398
+ dependency as a command failure. An unavailable destination reports its reason
399
+ and releases with `paused` after a `connected_runner_required` event.
400
+ Vendor export remains blocked.
401
+
402
+ The current MCP `next_question` filters out owner items. When an owner summary
403
+ is supplied, the CLI displays its browser link and refuses to answer it.
404
+
405
+ The four deterministic adapter implementations and their native output formats
406
+ are described in [the adapter guide](cli/business/vendors/README.md). Their
407
+ presence does not enable export until the seed import authority and remaining
408
+ transport contracts are connected.
package/cli/README.md CHANGED
@@ -346,6 +346,38 @@ Both forms write one JSON document with schema `rer-business-signals/1`,
346
346
  `source: "local"`, a `signals` array and a numeric `withheld` count. Each signal
347
347
  has `kind`, `value` (a name), relative `locator`, repository basename `repo`,
348
348
  `class` (`live-use` or `trace` for examples/comments), and `observedAt`.
349
+ Identical `(kind, value, repo, class)` signals are emitted once with an occurrence
350
+ `count` and the first matching `locator`. `secret-file` signals are exempt: each
351
+ denied file keeps its own path, size and modification time.
352
+
353
+ A nested checkout with its own `.git` directory starts a new repository: its
354
+ signals use that directory's basename and locators relative to it. Gitdir files
355
+ for submodules also start repository boundaries; below each scan root,
356
+ linked worktrees are skipped without following their gitdir pointers. Agent
357
+ and editor folders such as
358
+ `.claude/`, `.codex/`, `.cursor/`, `.worktrees/`, `.idea/`, `.vscode/`,
359
+ `.windsurf/` and `.continue/` are also skipped below each scan root. A
360
+ caller-named linked worktree or tool directory is scanned, as is a root beneath
361
+ tool directories.
362
+ The document's `skipped` object counts pruned boundaries by kind:
363
+ `linkedWorktrees`, `toolDirectories`, `generatedDirectories` (including
364
+ dependencies), and `gitDirectories`. These counts contain no paths and count
365
+ only the skipped boundary, not anything inside it. Git metadata below a scan
366
+ root, including `.git/worktrees/`, is never walked. A root that is itself a
367
+ `.git` directory is refused with a nonzero exit status and no paths in the
368
+ output. Generated and vendored trees are excluded relative to each scan root,
369
+ so an explicitly named ordinary root remains scannable even below a directory
370
+ named `build` or `vendor`.
371
+
372
+ `config-key` observations come only from JSON (including JSONC), YAML and TOML
373
+ files in configuration directories (such as
374
+ `config/`, `.github/`, `deploy/`, `charts/`, `k8s/` and `infra/`) and known
375
+ configuration names (such as `wrangler.*`, `docker-compose*.yaml`, `settings.*`
376
+ and `*.config.json`). Test/fixture data, translations, locales, samples, exports,
377
+ lockfiles and generated files contribute no config keys, even under a config
378
+ directory. Each file contributes at most `configKeyLimit` distinct key paths;
379
+ the document declares that limit (currently 200). JavaScript and TypeScript
380
+ config files are not read or parsed; dependencies still come from manifests.
349
381
 
350
382
  This is names-only discovery: configuration values and file contents are not
351
383
  emitted. Denied secret files are never opened; their `secret-file` observations
@@ -0,0 +1,61 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+
3
+ export function originUrl(value = 'https://app.runeditrun.com') {
4
+ let url;
5
+ try { url = new URL(value); } catch { throw Error('Business origin must be an HTTPS origin.'); }
6
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
7
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local) || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
8
+ throw Error('Business origin must be an HTTPS origin (HTTP is allowed only on loopback).');
9
+ }
10
+ return url.origin;
11
+ }
12
+
13
+ export class ApiError extends Error {
14
+ constructor(status) {
15
+ super(status === 401 ? 'Business pairing was revoked or expired. Reconnect in your browser.' : `Business server refused the request (HTTP ${status}).`);
16
+ this.status = status;
17
+ }
18
+ }
19
+
20
+ export class Api {
21
+ constructor(origin, credential) { this.origin = originUrl(origin); this.credential = credential; }
22
+ async mintToken(audience, { taskId, signal } = {}) {
23
+ const result = await this.post('/api/business/executors/token', { audience, ...(taskId ? { task_id: identifier(taskId) } : {}) }, { signal });
24
+ const maximum = audience === 'mcp' ? 300 : 900;
25
+ if (typeof result?.access_token !== 'string' || !result.access_token.startsWith('bz_task_') || result.token_type !== 'Bearer'
26
+ || result.audience !== `${this.origin}/api/business/${audience}` || result.task_id !== (taskId ?? null)
27
+ || !Number.isInteger(result.expires_in) || result.expires_in < 1 || result.expires_in > maximum
28
+ || !Number.isFinite(Date.parse(result.expires_at)) || Date.parse(result.expires_at) <= Date.now()) throw Error('Business server returned an invalid scoped bearer.');
29
+ return result;
30
+ }
31
+ async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
32
+ if (!path.startsWith('/api/business/') || path.includes('..') || path.includes('?') || path.includes('#')) throw Error('Invalid Business route.');
33
+ let response;
34
+ try {
35
+ response = await fetch(this.origin + path, {
36
+ method: 'POST', redirect: 'error',
37
+ headers: { ...headers, 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
38
+ body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
39
+ });
40
+ } catch (error) { if (signal?.aborted) throw signal.reason; throw Error('Could not reach the Business server.'); }
41
+ if (!response.ok) { await response.body?.cancel(); throw new ApiError(response.status); }
42
+ // Never print server errors or evidence; even successful bodies are untrusted.
43
+ if (response.status === 202 && response.headers.get('content-length') === '0' || response.status === 204) return null;
44
+ const text = await response.text();
45
+ if (!text) return null;
46
+ if (text.length > 2_000_000) throw Error('Business response exceeded the limit.');
47
+ let result;
48
+ try { result = JSON.parse(text); } catch { throw Error('Business server returned an invalid response.'); }
49
+ return result && Object.hasOwn(result, 'data') ? result.data : result;
50
+ }
51
+ }
52
+
53
+ export async function pause(milliseconds, signal) {
54
+ await delay(milliseconds, undefined, { signal });
55
+ }
56
+
57
+ export function identifier(value) {
58
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,399}$/.test(value)) throw Error('Business server returned an invalid identifier.');
59
+ return value;
60
+ }
61
+ export const taskPath = (id, action) => `/api/business/tasks/${encodeURIComponent(identifier(id))}/${action}`;
@@ -1,27 +1,51 @@
1
- import { scan } from './scan.mjs';
1
+ import { scanCommand } from './scan-command.mjs';
2
+ import { connect } from './connect.mjs';
3
+ import { vendorKey, disconnect, status } from './local-commands.mjs';
4
+ import { next, answer, token } from './questions.mjs';
5
+ import { run } from './supervisor.mjs';
2
6
 
3
- const usage = 'Usage: rer business scan [DIR...] [--json]\nNames-only local discovery; returns rer-business-signals/1 JSON. No network calls.\n';
7
+ const usage = `Usage: rer business VERB
8
+ scan [DIR...] [--json] Names-only local discovery
9
+ connect --code CODE [--origin URL]
10
+ Pair, compare a number in your browser, then opt in to a service
11
+ run [--once] Run consented local discovery; vendor upload integration pending
12
+ next Return one templated question or nothing yet within 60 seconds
13
+ answer ID VENDOR USAGE [CONFIDENCE]
14
+ Catalogue vendor or none; uses, sells, both, product-dependency
15
+ vendor-key add|remove VENDOR Keep a vendor key in OS credential storage
16
+ token MCP headersHelper output; send directly to the MCP client
17
+ status [--json] Pairing, service, current task and checkpoint
18
+ disconnect Remove local service, credentials and added permissions
19
+ Vendors: sentry, uptimerobot, pagerduty, calendly. Owner approvals stay in the browser.
20
+ `;
4
21
 
5
22
  export async function businessCommand(argv) {
6
- if (!argv.length || argv.length === 1 && ['--help', '-h'].includes(argv[0]) || argv[0] === 'scan' && argv.slice(1).some(arg => ['--help', '-h'].includes(arg))) {
7
- process.stdout.write(usage); return 0;
8
- }
9
- if (argv[0] !== 'scan') { process.stderr.write(usage); return 2; }
10
- const directories = [];
11
- let positional = false, json = false;
12
- for (const arg of argv.slice(1)) {
13
- if (!positional && arg === '--') { positional = true; continue; }
14
- if (!positional && arg === '--json' && !json) { json = true; continue; }
15
- if (!positional && arg.startsWith('-') || !arg.trim()) { process.stderr.write(usage); return 2; }
16
- directories.push(arg);
17
- }
23
+ if (!argv.length || argv[0] !== 'scan' && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(usage); return 0; }
24
+ if (argv[0] === 'scan') return scanCommand(argv);
18
25
  try {
19
- const result = await scan(directories.length ? directories : [process.cwd()]);
20
- process.stdout.write(JSON.stringify(result) + '\n');
26
+ const [verb, ...args] = argv;
27
+ if (verb === 'connect') {
28
+ const options = {};
29
+ for (let index = 0; index < args.length; index += 2) {
30
+ const name = args[index];
31
+ if (!['--code', '--origin'].includes(name) || !args[index + 1] || args[index + 1].startsWith('--') || Object.hasOwn(options, name.slice(2))) return invalid();
32
+ options[name.slice(2)] = args[index + 1];
33
+ }
34
+ if (typeof options.code !== 'string' || !/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(options.code)) return invalid();
35
+ await connect(options);
36
+ } else if (verb === 'vendor-key' && args.length === 2) await vendorKey(...args);
37
+ else if (verb === 'answer' && [3, 4].includes(args.length)) await answer(...args);
38
+ else if (verb === 'run' && (!args.length || args.length === 1 && args[0] === '--once')) await run({ once: args[0] === '--once' });
39
+ else if (verb === 'status' && args.length === 1 && args[0] === '--json') await status({ json: true });
40
+ else if (!args.length && ['next','token','status','disconnect'].includes(verb)) await ({ next, token, status, disconnect })[verb]();
41
+ else return invalid();
21
42
  return 0;
22
- } catch {
23
- // Node/format errors can contain input paths, keys or source excerpts.
24
- process.stderr.write('Business scan could not read a local input. No scan document was emitted.\n');
25
- return 1;
43
+ } catch (error) {
44
+ // All messages emitted here are authored by this CLI, never server/vendor or
45
+ // OS diagnostics. Unexpected errors can contain paths or credential material.
46
+ const message = error instanceof Error && /^(?:Business |This computer |This item |Choose |OS credential |Enter |Credential |A terminal |Installing |Changing |Keeping |Could not (?:reach the Business|keep this Mac|start the Business|stop the Business|reload the Business)|Claude |The Business |A Business |Another process |Run rer )/.test(error.message)
47
+ ? error.message : 'Business command failed. Check pairing, OS credential storage and browser task requirements.';
48
+ process.stderr.write(message + '\n'); return 1;
26
49
  }
27
50
  }
51
+ function invalid() { process.stderr.write(usage); return 2; }
@@ -0,0 +1,25 @@
1
+ import { basename } from 'node:path';
2
+
3
+ export const configKeyLimit = 200;
4
+
5
+ const directories = new Set(['config', 'configs', 'configuration', 'conf', '.github', '.circleci', '.buildkite',
6
+ 'deploy', 'deployment', 'deployments', 'helm', 'chart', 'charts', 'k8s', 'kubernetes', 'terraform', 'infra', 'infrastructure']);
7
+ const dataDirectories = new Set(['fixture', 'fixtures', '__fixtures__', 'test', 'tests', '__tests__',
8
+ 'translation', 'translations', 'locale', 'locales', 'i18n', 'l10n', 'sample', 'samples', 'export', 'exports',
9
+ 'snapshot', 'snapshots', '__snapshots__', 'generated', 'output', 'dist', 'build', 'coverage']);
10
+
11
+ // Data locations override config names: fixtures/config/settings.json is still
12
+ // a fixture. This policy only controls config keys; vendor extractors still run.
13
+ export function configuration(path) {
14
+ const lower = path.toLowerCase(), parts = lower.split('/'), name = basename(lower);
15
+ if (parts.slice(0, -1).some(part => dataDirectories.has(part))) return false;
16
+ if (/(?:^|[._-])(?:lock|lockfile|generated|min|bundle)(?:[._-]|$)/.test(name) ||
17
+ /^(?:npm-shrinkwrap|composer\.lock|cargo\.lock)/.test(name)) return false;
18
+ return parts.slice(0, -1).some(part => directories.has(part)) ||
19
+ /^(?:docker-)?compose(?:[._-].*)?\.ya?ml$/.test(name) ||
20
+ /^(?:wrangler|serverless|settings|appsettings[^.]*|pulumi)\./.test(name) ||
21
+ /^(?:app\.(?:json|ya?ml)|vercel\.json|netlify\.toml|fly\.toml|render\.ya?ml|chart\.ya?ml|values(?:[._-].*)?\.ya?ml)$/.test(name) ||
22
+ /(?:^|\.)config\.(?:[cm]?[jt]s|jsonc?|ya?ml|toml)$/.test(name) ||
23
+ /^(?:\.gitlab-ci|azure-pipelines|\.travis|bitbucket-pipelines)(?:[._-].*)?\.ya?ml$/.test(name) ||
24
+ /^(?:tsconfig|jsconfig)(?:\.[^.]+)?\.json$/.test(name);
25
+ }
@@ -0,0 +1,50 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { Api, originUrl, identifier, pause } from './api.mjs';
4
+ import { loadState, saveState, credentialHandle } from './state.mjs';
5
+ import { createCredentialStore } from './keychain.mjs';
6
+ import { installService } from './service.mjs';
7
+ import { installPermissions } from './permissions.mjs';
8
+ import { consent } from './prompts.mjs';
9
+
10
+ export const capabilities = ['discover.local', 'export.vendor:sentry', 'export.vendor:uptimerobot', 'export.vendor:pagerduty', 'export.vendor:calendly'];
11
+
12
+ export async function connect({ code, origin }) {
13
+ origin = originUrl(origin);
14
+ if (await loadState()) throw Error('Business has local pairing state. Disconnect before pairing again.');
15
+ const store = createCredentialStore(), handle = credentialHandle(origin);
16
+ // Fail before redeeming the one-use browser code if the OS store is absent.
17
+ if (await store.get(handle)) throw Error('A Business credential already exists for this origin. Disconnect it before pairing again.');
18
+ const api = new Api(origin);
19
+ const pending = await api.post('/api/business/executors/pair', {
20
+ code, os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: 'other', capabilities,
21
+ });
22
+ if (pending.status !== 'pending_approval' || !/^\d{6}$/.test(pending.confirmation_number) || typeof pending.pairing_token !== 'string') throw Error('Business server returned an invalid pairing response.');
23
+ process.stdout.write(`Confirmation number: ${pending.confirmation_number}\nCompare this number in the browser that created the code, then approve. Waiting for browser approval.\n`);
24
+ const expires = Math.min(Date.now() + 600_000, Date.parse(pending.expires_at));
25
+ if (!Number.isFinite(expires)) throw Error('Business server returned an invalid pairing expiry.');
26
+ let result;
27
+ while (Date.now() < expires) {
28
+ result = await api.post('/api/business/executors/pair', { pairing_token: pending.pairing_token });
29
+ if (result.status === 'paired') break;
30
+ if (result.status !== 'authorization_pending') throw Error('Business server returned an invalid pairing status.');
31
+ await pause(Math.max(1, Math.min(5, Number(result.interval) || 5)) * 1000);
32
+ }
33
+ if (result?.status !== 'paired' || typeof result.device_credential !== 'string') throw Error('Browser approval expired. Create a new pairing code in the browser.');
34
+ const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false };
35
+ await store.set(handle, result.device_credential);
36
+ try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
37
+ process.stdout.write('Business paired. Device credential stored in OS keychain.\n');
38
+ if (await consent('Add secret-file Read deny rules to Claude Code user settings?')) await installPermissions({ consent: true });
39
+ if (process.platform === 'darwin') state.awakeConsent = await consent('Keep this Mac awake only while an export task lease is active?');
40
+ await saveState(state);
41
+ if (await consent('Install a user background service running rer business run after this chat?')) {
42
+ await installService({ consent: true });
43
+ process.stdout.write('Business background service installed.\n');
44
+ } else process.stdout.write('Run rer business run in a terminal to work tasks.\n');
45
+ }
46
+
47
+ export function localRoot(path) {
48
+ if (typeof path !== 'string' || !path || path.includes('\0')) throw Error('Task has an invalid consented scan root.');
49
+ return path === '~' ? homedir() : path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
50
+ }
@@ -0,0 +1,180 @@
1
+ import { constants } from 'node:fs';
2
+ import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { homedir } from 'node:os';
5
+ import { isAbsolute, join, resolve } from 'node:path';
6
+ import { identifier } from './api.mjs';
7
+ import { assertSignals } from './outbound.mjs';
8
+ import { scan } from './scan.mjs';
9
+
10
+ const PAGE_BYTES = 128 * 1024, QUOTA_BYTES = 2 * 1024 * 1024;
11
+ const hash = value => createHash('sha256').update(value).digest('hex');
12
+ const integer = value => Number.isSafeInteger(value) && value >= 0;
13
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
14
+ const fail = message => { throw Error(`Business discovery ${message}.`); };
15
+
16
+ // The scan command includes local counts and skip diagnostics. The executor
17
+ // upload contract accepts only the names-only signal projection.
18
+ function uploadDocument(result) {
19
+ return { schema: result.schema, source: result.source, withheld: result.withheld,
20
+ signals: result.signals.map(({ kind, value, locator, repo, class: sourceClass, observedAt, size, mtime }) => ({
21
+ kind, value, locator, repo, class: sourceClass, observedAt, ...(size === undefined ? {} : { size, mtime }),
22
+ })) };
23
+ }
24
+
25
+ function inputs(task, grant, checkpoint, stateDir) {
26
+ if (!object(task) || task.kind !== 'discover.local' || !object(grant)) fail('requires a scoped local discovery grant');
27
+ identifier(task.id); identifier(grant.id); identifier(grant.consent?.id);
28
+ if (grant.task_id !== task.id || !integer(task.fence) || task.fence < 1 || grant.fence !== task.fence) fail('grant does not match the claimed task and fence');
29
+ if (grant.destination !== `/api/business/tasks/${encodeURIComponent(task.id)}/uploads`) fail('grant has an invalid upload destination');
30
+ if (!integer(grant.quota_bytes) || grant.quota_bytes < 1 || grant.quota_bytes > QUOTA_BYTES || !integer(grant.uploaded_bytes) || grant.uploaded_bytes > grant.quota_bytes) fail('grant has invalid byte limits');
31
+ const paths = grant.consent.scope?.paths;
32
+ if (!Array.isArray(paths) || !paths.length || paths.some(path => typeof path !== 'string' || /[\u0000-\u001f\u007f]/u.test(path) || !(isAbsolute(path) || path.startsWith('~/')))) fail('consent must contain absolute or home-relative scoped paths');
33
+ // Only the browser-authorized grant supplies roots. Canonicalize spelling and
34
+ // order without following symlinks; scan itself refuses symlink ancestors.
35
+ const roots = [...new Set(paths.map(path => resolve(path.startsWith('~/') ? join(homedir(), path.slice(2)) : path)))].sort();
36
+ if (!isAbsolute(stateDir ?? '')) fail('requires an absolute private state directory');
37
+ if (!object(checkpoint) || Object.keys(checkpoint).some(key => !['page', 'total', 'records_done', 'bytes_done', 'progress'].includes(key))) fail('checkpoint is invalid');
38
+ for (const key of ['page', 'total', 'records_done', 'bytes_done']) if (checkpoint[key] !== undefined && !integer(checkpoint[key])) fail('checkpoint is invalid');
39
+ if (checkpoint.progress !== undefined && (!integer(checkpoint.progress) || checkpoint.progress > 100)) fail('checkpoint progress is invalid');
40
+ if (!checkpoint.page && (checkpoint.records_done || checkpoint.bytes_done)) fail('checkpoint lacks its acknowledged page');
41
+ return { roots, identity: hash(JSON.stringify([task.id, grant.consent.id, roots])) };
42
+ }
43
+
44
+ function validateDocument(document) {
45
+ if (!object(document) || document.schema !== 'rer-business-signals/1' || document.source !== 'local' || !Array.isArray(document.signals) || !integer(document.withheld) || Object.keys(document).some(key => !['schema', 'source', 'signals', 'withheld'].includes(key))) fail('snapshot document is invalid');
46
+ const allowed = ['kind', 'value', 'locator', 'repo', 'class', 'observedAt', 'size', 'mtime'];
47
+ for (const item of document.signals) {
48
+ if (!object(item) || Object.keys(item).some(key => !allowed.includes(key)) || ['kind', 'value', 'locator', 'repo', 'observedAt'].some(key => typeof item[key] !== 'string') || !['live-use', 'trace'].includes(item.class) || item.size !== undefined && !integer(item.size) || item.mtime !== undefined && typeof item.mtime !== 'string') fail('snapshot signal is invalid');
49
+ }
50
+ assertSignals(document);
51
+ }
52
+
53
+ const pageDocument = (document, start, end) => ({ schema: document.schema, source: document.source, signals: document.signals.slice(start, end), withheld: start === 0 ? document.withheld : 0 });
54
+
55
+ function paginate(document) {
56
+ const ends = [];
57
+ let start = 0, bytes = Buffer.byteLength(JSON.stringify(pageDocument(document, 0, 0)));
58
+ for (let index = 0; index < document.signals.length; index++) {
59
+ const signalBytes = Buffer.byteLength(JSON.stringify(document.signals[index]));
60
+ if (index - start >= 2000 || bytes + signalBytes + (index > start ? 1 : 0) >= PAGE_BYTES) {
61
+ if (index === start) fail('signal exceeds the upload page bound');
62
+ ends.push(index); start = index;
63
+ bytes = Buffer.byteLength(JSON.stringify(pageDocument(document, start, start)));
64
+ }
65
+ bytes += signalBytes + (index > start ? 1 : 0);
66
+ if (bytes >= PAGE_BYTES) fail('signal exceeds the upload page bound');
67
+ }
68
+ if (document.signals.length) ends.push(document.signals.length);
69
+ return ends;
70
+ }
71
+
72
+ function pagesFrom(snapshot, identity, quota) {
73
+ if (!object(snapshot) || snapshot.version !== 1 || snapshot.identity !== identity || !Array.isArray(snapshot.pageEnds)) fail('snapshot does not match this task and consent');
74
+ validateDocument(snapshot.document);
75
+ const pages = []; let start = 0, bytes = 0;
76
+ for (const end of snapshot.pageEnds) {
77
+ if (!integer(end) || end <= start || end > snapshot.document.signals.length) fail('snapshot pagination is invalid');
78
+ const document = pageDocument(snapshot.document, start, end), size = Buffer.byteLength(JSON.stringify(document));
79
+ if (size >= PAGE_BYTES) fail('snapshot exceeds the upload page bound');
80
+ bytes += size;
81
+ if (bytes > quota) fail('snapshot exceeds the consented upload quota');
82
+ pages.push({ document, bytes: size, records: end - start }); start = end;
83
+ }
84
+ if (start !== snapshot.document.signals.length) fail('snapshot pagination is incomplete');
85
+ return pages;
86
+ }
87
+
88
+ async function readSnapshot(path) {
89
+ let file;
90
+ try {
91
+ file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
92
+ const info = await file.stat();
93
+ if (!info.isFile() || info.size > QUOTA_BYTES + 256 * 1024) fail('snapshot is not a bounded regular file');
94
+ await file.chmod(0o600);
95
+ let snapshot;
96
+ try { snapshot = JSON.parse(await file.readFile('utf8')); }
97
+ catch { fail('snapshot is unreadable; keep it intact and restart with a new consent'); }
98
+ return snapshot;
99
+ } catch (error) {
100
+ if (error.code === 'ENOENT') return null;
101
+ // Filesystem errors can contain names; never surface them as diagnostics.
102
+ if (error.message?.startsWith('Business discovery ')) throw error;
103
+ fail('could not read its private snapshot');
104
+ } finally { await file?.close(); }
105
+ }
106
+
107
+ async function writeSnapshot(directory, path, snapshot) {
108
+ const temporary = join(directory, `discovery-${randomUUID()}.tmp`);
109
+ let file, directoryFile;
110
+ try {
111
+ file = await open(temporary, 'wx', 0o600);
112
+ await file.writeFile(JSON.stringify(snapshot)); await file.sync(); await file.close(); file = undefined;
113
+ await rename(temporary, path);
114
+ directoryFile = await open(directory, constants.O_RDONLY);
115
+ await directoryFile.sync();
116
+ } catch { fail('could not durably save its private snapshot; no upload was started'); }
117
+ finally {
118
+ await file?.close(); await directoryFile?.close();
119
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') fail('could not clean up its temporary snapshot'); });
120
+ }
121
+ }
122
+
123
+ function counts(pages, page) {
124
+ const acknowledged = pages.slice(0, page);
125
+ return { page, total: pages.length, records_done: acknowledged.reduce((sum, item) => sum + item.records, 0), bytes_done: acknowledged.reduce((sum, item) => sum + item.bytes, 0), progress: pages.length ? Math.floor(page / pages.length * 100) : 100 };
126
+ }
127
+
128
+ /** send adds the current fence/grant/token to the supplied upload payload.
129
+ * The server checkpoint is authoritative. Keep the snapshot until the caller
130
+ * receives completion acknowledgement, then invoke the returned cleanup().
131
+ */
132
+ export async function runDiscovery({ task, grant, checkpoint = task?.checkpoint ?? {}, signal, send, saveCheckpoint, stateDir }) {
133
+ signal?.throwIfAborted();
134
+ const { roots, identity } = inputs(task, grant, checkpoint, stateDir);
135
+ if (typeof send !== 'function' || typeof saveCheckpoint !== 'function') fail('requires upload and checkpoint callbacks');
136
+ const path = join(stateDir, `discovery-${identity}.json`);
137
+ try {
138
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
139
+ const info = await lstat(stateDir);
140
+ if (!info.isDirectory() || info.isSymbolicLink()) fail('state directory must be private and regular');
141
+ await chmod(stateDir, 0o700);
142
+ } catch { fail('could not prepare its private state directory'); }
143
+ let snapshot = await readSnapshot(path);
144
+ if (!snapshot) {
145
+ if (checkpoint.page > 0) fail('cannot resume acknowledged pages without the original snapshot; restore it or start a new consent');
146
+ let document;
147
+ try { document = uploadDocument(await scan(roots)); }
148
+ catch { fail('could not read a consented local input; no upload was started'); }
149
+ signal?.throwIfAborted();
150
+ validateDocument(document);
151
+ snapshot = { version: 1, identity, document, pageEnds: paginate(document) };
152
+ pagesFrom(snapshot, identity, grant.quota_bytes);
153
+ await writeSnapshot(stateDir, path, snapshot);
154
+ }
155
+ const pages = pagesFrom(snapshot, identity, grant.quota_bytes), page = checkpoint.page ?? 0;
156
+ if (page > pages.length) fail('checkpoint is outside its saved pagination');
157
+ if (grant.uploaded_bytes + pages.slice(page).reduce((sum, item) => sum + item.bytes, 0) > grant.quota_bytes) fail('remaining pages exceed the granted upload quota');
158
+ const expected = counts(pages, page);
159
+ for (const key of ['total', 'records_done', 'bytes_done']) {
160
+ // A fresh server task can project zero counters before a plan exists.
161
+ if (key === 'total' && page === 0 && checkpoint.total === 0) continue;
162
+ if (checkpoint[key] !== undefined && checkpoint[key] !== expected[key]) fail('checkpoint disagrees with its saved snapshot');
163
+ }
164
+ for (let index = page; index < pages.length; index++) {
165
+ signal?.throwIfAborted();
166
+ // A renewed grant has a new idempotency namespace. Retries under the same
167
+ // grant reuse the exact event id and immutable document bytes.
168
+ const digest = hash(JSON.stringify([identity, grant.id, grant.fence, index, pages[index].document]));
169
+ const eventId = `${digest.slice(0, 8)}-${digest.slice(8, 12)}-${digest.slice(12, 16)}-${digest.slice(16, 20)}-${digest.slice(20, 32)}`;
170
+ const payload = { client_event_id: eventId, consent_id: grant.consent.id, document: pages[index].document };
171
+ assertSignals(payload.document);
172
+ if (Buffer.byteLength(JSON.stringify({ ...payload, fence: grant.fence, grant_id: grant.id })) > QUOTA_BYTES) fail('upload request exceeds the protocol bound');
173
+ await send(grant.destination, payload);
174
+ await saveCheckpoint(counts(pages, index + 1));
175
+ }
176
+ if (!pages.length) { signal?.throwIfAborted(); await saveCheckpoint(counts(pages, 0)); }
177
+ return { ...counts(pages, pages.length), cleanup: async () => {
178
+ await unlink(path).catch(error => { if (error.code !== 'ENOENT') fail('could not remove its completed snapshot'); });
179
+ } };
180
+ }
@@ -0,0 +1,25 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open } from 'node:fs/promises';
3
+ import { dirname, join, parse } from 'node:path';
4
+
5
+ // Caller-named roots are canonicalized once; below them, refuse symlink
6
+ // ancestors as well as symlink entries before reading any file content.
7
+ async function plainAncestors(path) {
8
+ const root = parse(path).root;
9
+ let current = root;
10
+ for (const part of path.slice(root.length).split('/').filter(Boolean)) {
11
+ current = join(current, part);
12
+ if ((await lstat(current)).isSymbolicLink()) return false;
13
+ }
14
+ return true;
15
+ }
16
+
17
+ export async function readPlainFile(path, info) {
18
+ // O_NOFOLLOW blocks a replaced leaf; compare the opened inode before reading.
19
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
20
+ try {
21
+ const opened = await file.stat();
22
+ if (!opened.isFile() || opened.ino !== info.ino || opened.dev !== info.dev || !await plainAncestors(dirname(path))) throw Error('Changed scan input');
23
+ return await file.readFile('utf8');
24
+ } finally { await file.close(); }
25
+ }