@brunobracaioli/aibrain 0.4.0-beta.32 → 0.4.0-beta.33

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.
@@ -0,0 +1,232 @@
1
+ // @ts-check
2
+ /**
3
+ * What the `autonomous` profile adds to one Claude Code launch (spec
4
+ * aisac-engineering-autonomy FR2): `--permission-mode auto` unless the user chose a
5
+ * mode, a generated `autoMode` block, a small deny baseline, and the manager's own
6
+ * send and cancel tools for a manager launch. Everything goes into the launch's
7
+ * private `--settings` file; the user's host files are never written.
8
+ *
9
+ * The classifier is not a boundary (AU0, spec §9.1 s7 and s11): explicit requests
10
+ * override its soft blocks. The deny baseline here, the catalog deny rules and the
11
+ * guardrails are what refuse; the `autoMode` prose only reduces noise.
12
+ */
13
+ import { execFile } from 'node:child_process';
14
+ import { dirname, isAbsolute } from 'node:path';
15
+ import { MANAGER_SERVER_NAME } from './manager/launch-role.mjs';
16
+
17
+ /**
18
+ * Deny rules every `autonomous` Claude launch adds (FR2). They hold in every
19
+ * permission mode, auto included (AU0 s10).
20
+ */
21
+ export const CLAUDE_DENY_BASELINE = Object.freeze([
22
+ 'Bash(sudo *)',
23
+ 'Bash(su *)',
24
+ 'Bash(doas *)',
25
+ 'Bash(git push --force *)',
26
+ 'Bash(git push -f *)',
27
+ 'Bash(git reset --hard *)',
28
+ 'Bash(git clean -fd *)',
29
+ ]);
30
+
31
+ /** A manager's sends and cancels need no prompt under `autonomous` (FR2, criterion 3). */
32
+ export const MANAGER_SEND_ALLOW = Object.freeze([
33
+ `mcp__${MANAGER_SERVER_NAME}__manager_send`,
34
+ `mcp__${MANAGER_SERVER_NAME}__manager_cancel`,
35
+ ]);
36
+
37
+ /** Native flags that choose a permission mode; the user's choice wins (FR2.1). */
38
+ const MODE_FLAGS = new Set(['--permission-mode', '--dangerously-skip-permissions']);
39
+
40
+ /** One line per reserve class, for `autoMode.soft_deny` (FR2). */
41
+ const RESERVE_PROSE = Object.freeze([
42
+ 'Reading, printing or copying secrets, tokens, private keys or .env files.',
43
+ 'Pushing to main or master, force pushing, deleting remote branches or rewriting published history.',
44
+ 'Deleting or overwriting data outside this repository, or dropping, truncating or resetting databases.',
45
+ 'Publishing packages, deploying, creating releases, sending messages or emails, or calling paid APIs.',
46
+ 'Using sudo, su or doas, or changing users, groups, system services or file ownership.',
47
+ 'Changing Claude Code permissions, hooks, sandbox or settings files.',
48
+ 'Writing files outside this repository, its worktrees and the temporary directory.',
49
+ 'Running obfuscated or encoded commands whose effect cannot be read.',
50
+ ]);
51
+
52
+ /** The classes that are never right for an unattended session, as `hard_deny` prose. */
53
+ const HARD_DENY_PROSE = Object.freeze([
54
+ 'Publishing packages, deploying to production, creating releases, sending messages or emails, or spending money.',
55
+ 'Using sudo, su or doas, or changing users, groups or system services.',
56
+ 'Pushing to main or master, or force pushing to any branch.',
57
+ ]);
58
+
59
+ const SENSITIVE_PROSE =
60
+ 'Sensitive: anything named prod or production (branches, hosts, databases, deployments, environments).';
61
+ const RESERVE_SUMMARY =
62
+ 'Held for the human, never done unattended: secrets; pushes to the default branch, force pushes and history rewrites; destructive deletes; publishing, deploying, messaging or spending; privilege changes; permission or settings changes; writes outside the repository.';
63
+ const MAX_PATH_LENGTH = 1024;
64
+ const MAX_REMOTE_HOSTS = 8;
65
+ const MAX_REMOTE_URL_LENGTH = 2048;
66
+ const GIT_TIMEOUT_MS = 2000;
67
+ const GIT_MAX_BUFFER = 64 * 1024;
68
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u;
69
+ const HOST_NAME = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])$/u;
70
+ const URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//iu;
71
+ const SCP_REMOTE = /^(?:[A-Za-z0-9._-]+@)?([A-Za-z0-9.-]+):(?!\/\/)/u;
72
+
73
+ /**
74
+ * @typedef {object} RepositoryFacts
75
+ * @property {string | null} worktreeRoot the top of the checkout this session runs in
76
+ * @property {string | null} repositoryRoot the main checkout, when the session runs in a linked worktree
77
+ * @property {string[]} remoteHosts host names only, never a URL
78
+ */
79
+
80
+ /**
81
+ * Whether the user chose a permission mode for this launch: a native mode flag
82
+ * before any `--`, or `permissions.defaultMode` in the user's `--settings` fragment.
83
+ * @param {readonly string[]} args @param {Record<string, unknown> | undefined} userPermissions
84
+ */
85
+ export function userChosePermissionMode(args, userPermissions) {
86
+ for (const argument of args) {
87
+ if (argument === '--') break;
88
+ if (MODE_FLAGS.has(argument.split('=', 1)[0] ?? '')) return true;
89
+ }
90
+ return userPermissions !== undefined && Object.hasOwn(userPermissions, 'defaultMode');
91
+ }
92
+
93
+ /**
94
+ * The host name of a git remote, or null. URLs that carry credentials (an http
95
+ * user or any password) are dropped whole, so nothing of them reaches the host.
96
+ * @param {unknown} url @returns {string | null}
97
+ */
98
+ export function remoteHost(url) {
99
+ if (typeof url !== 'string' || url.length === 0 || url.length > MAX_REMOTE_URL_LENGTH)
100
+ return null;
101
+ if (CONTROL_CHARACTERS.test(url)) return null;
102
+ /** @type {string} */
103
+ let host;
104
+ if (URL_SCHEME.test(url)) {
105
+ let parsed;
106
+ try {
107
+ parsed = new URL(url);
108
+ } catch {
109
+ return null;
110
+ }
111
+ if (parsed.password !== '') return null;
112
+ if ((parsed.protocol === 'https:' || parsed.protocol === 'http:') && parsed.username !== '')
113
+ return null;
114
+ host = parsed.hostname;
115
+ } else {
116
+ const scp = SCP_REMOTE.exec(url);
117
+ if (scp === null) return null;
118
+ host = scp[1] ?? '';
119
+ }
120
+ host = host.toLowerCase();
121
+ return HOST_NAME.test(host) ? host : null;
122
+ }
123
+
124
+ /** @param {unknown} value @returns {string | null} */
125
+ function safePath(value) {
126
+ if (typeof value !== 'string') return null;
127
+ const path = value.trim();
128
+ if (path.length === 0 || path.length > MAX_PATH_LENGTH) return null;
129
+ if (!isAbsolute(path) || CONTROL_CHARACTERS.test(path)) return null;
130
+ return path;
131
+ }
132
+
133
+ /**
134
+ * Run git read-only, with a timeout and no prompt. Resolves to stdout, or null.
135
+ * @param {string[]} args @param {string} cwd @returns {Promise<string | null>}
136
+ */
137
+ export function runGit(args, cwd) {
138
+ return new Promise((resolvePromise) => {
139
+ execFile(
140
+ 'git',
141
+ args,
142
+ {
143
+ cwd,
144
+ timeout: GIT_TIMEOUT_MS,
145
+ maxBuffer: GIT_MAX_BUFFER,
146
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
147
+ windowsHide: true,
148
+ },
149
+ (error, stdout) => resolvePromise(error ? null : String(stdout)),
150
+ );
151
+ });
152
+ }
153
+
154
+ /**
155
+ * The fixed facts `autoMode.environment` is built from: the checkout roots and the
156
+ * remote host names. No file content, no branch name, no URL.
157
+ * @param {string} cwd @param {typeof runGit} [run]
158
+ * @returns {Promise<RepositoryFacts>}
159
+ */
160
+ export async function readRepositoryFacts(cwd, run = runGit) {
161
+ const roots = await run(
162
+ ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'],
163
+ cwd,
164
+ );
165
+ if (roots === null) return { worktreeRoot: null, repositoryRoot: null, remoteHosts: [] };
166
+ const [top, common] = roots.split('\n');
167
+ const worktreeRoot = safePath(top);
168
+ const commonDir = safePath(common);
169
+ const mainRoot =
170
+ commonDir !== null && /[\\/]\.git$/u.test(commonDir) ? safePath(dirname(commonDir)) : null;
171
+ const repositoryRoot = mainRoot !== null && mainRoot !== worktreeRoot ? mainRoot : null;
172
+ const remotes = (await run(['config', '--get-regexp', '^remote\\..*\\.url$'], cwd)) ?? '';
173
+ /** @type {string[]} */
174
+ const remoteHosts = [];
175
+ for (const line of remotes.split('\n')) {
176
+ const url = line.slice(line.indexOf(' ') + 1);
177
+ const host = line.includes(' ') ? remoteHost(url) : null;
178
+ if (host !== null && !remoteHosts.includes(host)) remoteHosts.push(host);
179
+ if (remoteHosts.length === MAX_REMOTE_HOSTS) break;
180
+ }
181
+ return { worktreeRoot, repositoryRoot, remoteHosts };
182
+ }
183
+
184
+ /**
185
+ * `autoMode.environment`: truthful prose about this launch (FR2).
186
+ * @param {RepositoryFacts} facts @returns {string[]}
187
+ */
188
+ export function autoModeEnvironment(facts) {
189
+ /** @type {string[]} */
190
+ const lines = [];
191
+ if (facts.worktreeRoot === null)
192
+ lines.push(
193
+ 'No git repository was found: only the directory this session started in is in scope.',
194
+ );
195
+ else {
196
+ lines.push(
197
+ facts.repositoryRoot === null
198
+ ? `Trusted repository: the git repository at ${facts.worktreeRoot}, where this session started.`
199
+ : `Trusted repository: the git worktree at ${facts.worktreeRoot}, a checkout of the repository at ${facts.repositoryRoot}, where this session started.`,
200
+ );
201
+ lines.push(
202
+ facts.remoteHosts.length === 0
203
+ ? 'The repository has no remote that names a host.'
204
+ : `Its own remotes are on: ${facts.remoteHosts.join(', ')}. Feature branches may be pushed there; the default branch may not.`,
205
+ );
206
+ }
207
+ lines.push(SENSITIVE_PROSE, RESERVE_SUMMARY);
208
+ lines.push(
209
+ 'This session may run unattended, with a manager session giving it tasks; held actions are reviewed by the human later.',
210
+ );
211
+ return lines;
212
+ }
213
+
214
+ /**
215
+ * The `autonomous` layer of one Claude launch (FR2), without the sandbox (D7) and
216
+ * without `denyInsteadOfPrompting`, which only a night window adds (AU2).
217
+ * @param {{ args: readonly string[], userPermissions: Record<string, unknown> | undefined, facts: RepositoryFacts, manager: boolean }} input
218
+ */
219
+ export function claudeAutonomyLayer(input) {
220
+ const userMode = userChosePermissionMode(input.args, input.userPermissions);
221
+ return {
222
+ userMode,
223
+ modeArgs: userMode ? [] : ['--permission-mode', 'auto'],
224
+ deny: [...CLAUDE_DENY_BASELINE],
225
+ allow: input.manager ? [...MANAGER_SEND_ALLOW] : [],
226
+ autoMode: {
227
+ environment: autoModeEnvironment(input.facts),
228
+ soft_deny: ['$defaults', ...RESERVE_PROSE],
229
+ hard_deny: [...HARD_DENY_PROSE],
230
+ },
231
+ };
232
+ }
@@ -0,0 +1,99 @@
1
+ // @ts-check
2
+ /**
3
+ * Fixed text for the autonomy profile's outcomes (spec aisac-engineering-autonomy
4
+ * FR12): every line says what happened and what to do next, in pt-BR or English.
5
+ * The text takes only values this client validated: a host name, a catalog hook id
6
+ * and a profile name. Pure functions, no I/O.
7
+ */
8
+
9
+ /** @typedef {'pt-BR' | 'en'} AutonomyLocale */
10
+
11
+ const SWITCH_COMMAND = 'aisac setup --profile assisted';
12
+
13
+ /**
14
+ * The launch lines of a session whose profile is `autonomous`.
15
+ * @param {{ host: 'claude' | 'codex', active: boolean, userMode: boolean, offByChoice: readonly string[], locale: AutonomyLocale }} input
16
+ * @returns {string[]}
17
+ */
18
+ export function autonomyLaunchLines(input) {
19
+ const pt = input.locale === 'pt-BR';
20
+ if (!input.active)
21
+ return [
22
+ pt
23
+ ? 'Perfil autonomous: os guardrails do AISAC Engineering não carregaram neste lançamento, então esta sessão roda como assisted. Próximo passo: rode `aisac doctor` para ver a licença e os guardrails.'
24
+ : 'Profile autonomous: the AISAC Engineering guardrails did not load in this launch, so this session runs assisted. Next: run `aisac doctor` to check the license and the guardrails.',
25
+ ];
26
+ /** @type {string[]} */
27
+ const lines = [];
28
+ if (input.host === 'claude')
29
+ lines.push(
30
+ input.userMode
31
+ ? pt
32
+ ? `Perfil autonomous: o seu modo de permissão foi mantido; a lista de bloqueios e todos os guardrails estão ligados. Para voltar a ser perguntado como antes: ${SWITCH_COMMAND}.`
33
+ : `Profile autonomous: your own permission mode is kept; the deny baseline and every guardrail are on. To be asked as before: ${SWITCH_COMMAND}.`
34
+ : pt
35
+ ? `Perfil autonomous: Claude Code em modo auto, com a lista de bloqueios e todos os guardrails ligados. Para voltar a ser perguntado como antes: ${SWITCH_COMMAND}.`
36
+ : `Profile autonomous: Claude Code runs in auto mode, with the deny baseline and every guardrail on. To be asked as before: ${SWITCH_COMMAND}.`,
37
+ );
38
+ else
39
+ lines.push(
40
+ pt
41
+ ? `Perfil autonomous: todos os guardrails estão ligados no Codex. Para voltar ao de antes: ${SWITCH_COMMAND}.`
42
+ : `Profile autonomous: every guardrail is on for Codex. To go back: ${SWITCH_COMMAND}.`,
43
+ );
44
+ for (const id of input.offByChoice)
45
+ lines.push(
46
+ pt
47
+ ? `O ${id} está desligado por escolha sua e não recusa nada nesta sessão. Para ligá-lo: aisac hooks enable ${id}.`
48
+ : `${id} is off by your choice and refuses nothing in this session. To turn it on: aisac hooks enable ${id}.`,
49
+ );
50
+ return lines;
51
+ }
52
+
53
+ /**
54
+ * The guide of a refused profile flag or value: nothing was started or changed.
55
+ * @param {string} code @param {AutonomyLocale} locale @returns {string | null}
56
+ */
57
+ export function describeProfileError(code, locale) {
58
+ const pt = locale === 'pt-BR';
59
+ if (code === 'profile_flag_conflict')
60
+ return pt
61
+ ? 'Use --autonomous ou --assisted, uma única vez, antes de `--`. Nada foi iniciado. Exemplo: aisac claude --autonomous'
62
+ : 'Use --autonomous or --assisted, once, before `--`. Nothing was started. Example: aisac claude --autonomous';
63
+ if (code === 'profile_flag_has_no_value')
64
+ return pt
65
+ ? '--autonomous e --assisted não recebem valor. Nada foi iniciado. Exemplo: aisac codex --assisted'
66
+ : '--autonomous and --assisted take no value. Nothing was started. Example: aisac codex --assisted';
67
+ if (code === 'profile_invalid' || code === 'option_value_required:--profile')
68
+ return pt
69
+ ? 'O perfil é assisted ou autonomous. Nada foi alterado. Exemplo: aisac setup --profile autonomous'
70
+ : 'The profile is assisted or autonomous. Nothing was changed. Example: aisac setup --profile autonomous';
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * The line after setup recorded the profile. `offline` when `--profile` alone changed
76
+ * only the profile, without the network.
77
+ * @param {'assisted' | 'autonomous'} profile @param {string} root @param {AutonomyLocale} locale
78
+ * @param {boolean} [offline]
79
+ */
80
+ export function profileSetLine(profile, root, locale, offline = false) {
81
+ const other = profile === 'autonomous' ? 'assisted' : 'autonomous';
82
+ const effect =
83
+ profile === 'autonomous'
84
+ ? locale === 'pt-BR'
85
+ ? 'as próximas sessões do aisac rodam com menos perguntas: modo auto no Claude Code, lista de bloqueios e todos os guardrails'
86
+ : 'future aisac sessions ask less: auto mode in Claude Code, the deny baseline and every guardrail'
87
+ : locale === 'pt-BR'
88
+ ? 'as próximas sessões do aisac perguntam como os hosts perguntam por conta própria'
89
+ : 'future aisac sessions ask as the hosts do on their own';
90
+ const network =
91
+ offline === true
92
+ ? locale === 'pt-BR'
93
+ ? ' Nenhuma chamada de rede foi feita.'
94
+ : ' No network call was made.'
95
+ : '';
96
+ return locale === 'pt-BR'
97
+ ? `Perfil ${profile} gravado em ${root}/engineering-profile.json; ${effect}. Sessões abertas não mudam.${network} Para trocar: aisac setup --profile ${other}.`
98
+ : `Profile ${profile} recorded in ${root}/engineering-profile.json; ${effect}. Open sessions do not change.${network} To switch: aisac setup --profile ${other}.`;
99
+ }
@@ -0,0 +1,92 @@
1
+ // @ts-check
2
+ /**
3
+ * The autonomy profile (spec aisac-engineering-autonomy D1, FR1). `assisted` keeps
4
+ * the hosts' own prompts; `autonomous` adds the per-launch layer of FR2–FR4 to every
5
+ * session `aisac` launches. Setup stores the choice in
6
+ * `<state>/engineering-profile.json` (mode 0600, like the pack language); a launch
7
+ * flag overrides it for one session. Nothing is written into the user's host files.
8
+ */
9
+ import { join } from 'node:path';
10
+ import { readSmallStateJson } from './engineering-pack.mjs';
11
+ import { atomicJson } from './state.mjs';
12
+
13
+ /** @typedef {'assisted' | 'autonomous'} AutonomyProfile */
14
+ /** @typedef {'flag' | 'setup' | 'default'} ProfileSource */
15
+
16
+ export const PROFILE_FILE = 'engineering-profile.json';
17
+ const PROFILE_SCHEMA_VERSION = 1;
18
+ /** Existing setups read as `assisted` until the user chooses (FR1). */
19
+ export const DEFAULT_PROFILE = /** @type {AutonomyProfile} */ ('assisted');
20
+ /** A first setup without an answer gets `autonomous` (owner decision Q2). */
21
+ export const NEW_SETUP_PROFILE = /** @type {AutonomyProfile} */ ('autonomous');
22
+ /**
23
+ * The launch flags. Codex owns `--profile` and `-p` (its config profiles), so the
24
+ * launcher takes one word per profile instead of `--profile <p>`.
25
+ */
26
+ export const AUTONOMOUS_FLAG = '--autonomous';
27
+ export const ASSISTED_FLAG = '--assisted';
28
+
29
+ /** @param {unknown} value @returns {value is AutonomyProfile} */
30
+ export function isAutonomyProfile(value) {
31
+ return value === 'assisted' || value === 'autonomous';
32
+ }
33
+
34
+ /** @param {string} root @returns {Promise<AutonomyProfile | null>} */
35
+ export async function readStoredProfile(root) {
36
+ const value = await readSmallStateJson(join(root, PROFILE_FILE));
37
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
38
+ const record = /** @type {Record<string, unknown>} */ (value);
39
+ return record.schemaVersion === PROFILE_SCHEMA_VERSION && isAutonomyProfile(record.profile)
40
+ ? record.profile
41
+ : null;
42
+ }
43
+
44
+ /** @param {string} root @param {AutonomyProfile} profile */
45
+ export async function writeStoredProfile(root, profile) {
46
+ if (!isAutonomyProfile(profile)) throw new Error('profile_invalid');
47
+ await atomicJson(join(root, PROFILE_FILE), {
48
+ schemaVersion: PROFILE_SCHEMA_VERSION,
49
+ profile,
50
+ });
51
+ }
52
+
53
+ /**
54
+ * Take `--autonomous` or `--assisted` from the launcher's own arguments, before any
55
+ * `--`. Both, or either twice, is a usage error that starts nothing.
56
+ * @param {string[]} args
57
+ * @returns {{ profile: AutonomyProfile | null, args: string[] }}
58
+ */
59
+ export function takeProfileFlag(args) {
60
+ /** @type {string[]} */
61
+ const rest = [];
62
+ /** @type {AutonomyProfile | null} */
63
+ let profile = null;
64
+ for (let index = 0; index < args.length; index += 1) {
65
+ const argument = args[index] ?? '';
66
+ if (argument === '--') {
67
+ rest.push(...args.slice(index));
68
+ break;
69
+ }
70
+ if (argument.startsWith(`${AUTONOMOUS_FLAG}=`) || argument.startsWith(`${ASSISTED_FLAG}=`))
71
+ throw new Error('profile_flag_has_no_value');
72
+ if (argument === AUTONOMOUS_FLAG || argument === ASSISTED_FLAG) {
73
+ if (profile !== null) throw new Error('profile_flag_conflict');
74
+ profile = argument === AUTONOMOUS_FLAG ? 'autonomous' : 'assisted';
75
+ continue;
76
+ }
77
+ rest.push(argument);
78
+ }
79
+ return { profile, args: rest };
80
+ }
81
+
82
+ /**
83
+ * The profile a launch uses and where it came from (FR1): the flag, then the
84
+ * stored choice, then `assisted`.
85
+ * @param {{ flag: AutonomyProfile | null, stored: AutonomyProfile | null }} input
86
+ * @returns {{ profile: AutonomyProfile, source: ProfileSource }}
87
+ */
88
+ export function resolveProfile(input) {
89
+ if (input.flag !== null) return { profile: input.flag, source: 'flag' };
90
+ if (input.stored !== null) return { profile: input.stored, source: 'setup' };
91
+ return { profile: DEFAULT_PROFILE, source: 'default' };
92
+ }
@@ -16,7 +16,7 @@ export const MAX_LOG_FILES = 3;
16
16
  const LOCK_WAIT_MS = 250;
17
17
  const LOCK_STALE_MS = 30_000;
18
18
  const ADMISSION_MS = 60 * 60 * 1000;
19
- export const ADAPTER_VERSION = '0.4.0-beta.32';
19
+ export const ADAPTER_VERSION = '0.4.0-beta.33';
20
20
  const MAX_DIAGNOSTIC_COUNT = 10_000_000;
21
21
  const MAX_DIAGNOSTIC_BYTES = 128 * 1024 * 1024;
22
22
  const CHECKPOINT_BACKENDS = new Set(['native_store', 'private_file']);
package/dist/cli.mjs CHANGED
@@ -94,6 +94,16 @@ import { readCodexGuardrails } from './guardrails-plugin.mjs';
94
94
  import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
95
95
  import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
96
96
  import { resourcesDoctorLine, resourcesDoctorSection, runResources } from './resources.mjs';
97
+ import {
98
+ NEW_SETUP_PROFILE,
99
+ isAutonomyProfile,
100
+ readStoredProfile,
101
+ resolveProfile,
102
+ takeProfileFlag,
103
+ writeStoredProfile,
104
+ } from './autonomy-profile.mjs';
105
+ import { describeProfileError, profileSetLine } from './autonomy-next.mjs';
106
+ import { auditHostConfig, hostConfigDoctorLines } from './host-config-audit.mjs';
97
107
  import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
98
108
  import {
99
109
  describeClientNotConfigured,
@@ -104,7 +114,7 @@ import {
104
114
  } from './launch-feedback.mjs';
105
115
  import { parseCodexLaunchArgs } from './codex-permissions.mjs';
106
116
 
107
- const VERSION = '0.4.0-beta.32';
117
+ const VERSION = '0.4.0-beta.33';
108
118
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
109
119
  const COMMAND = 'aisac';
110
120
  /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
@@ -115,7 +125,7 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
115
125
 
116
126
  function usage() {
117
127
  console.log(
118
- `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} setup --login\n ${COMMAND} doctor [--json]\n ${COMMAND} resources [--json] [--sizes]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
128
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--paste-token | --token-file PATH]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system] [--profile assisted|autonomous]\n ${COMMAND} setup --login\n ${COMMAND} doctor [--json]\n ${COMMAND} resources [--json] [--sizes]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--autonomous | --assisted]\n [--manager | --worker <name> [--bus]] [--room <name>] [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--autonomous | --assisted]\n [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
119
129
  );
120
130
  console.log(
121
131
  '`aisac setup` signs in through the browser at a terminal; use `--paste-token` for the manual prompt, `--token-file` for automation, or `aisac setup --login` to replace an existing login.',
@@ -147,6 +157,9 @@ function usage() {
147
157
  console.log(
148
158
  'Updates: at launch `aisac` reads the signed release manifest and, in `auto` mode, installs the newer listed version into its own npm prefix and restarts; `notify` (the default) prints the command; `off` stays quiet. `aisac update` does it on demand (`--check` only looks, `--rollback` returns to the previous version, `--yes` for scripts); setup --update-mode and --channel record the choice; AISAC_NO_SELF_UPDATE=1 turns it off for one launch.',
149
159
  );
160
+ console.log(
161
+ "Autonomy profile (licensed accounts): `aisac setup --profile autonomous` makes every aisac session ask less: Claude Code runs in auto mode with a generated autoMode block and a deny baseline, and every guardrail is on; `assisted` keeps the hosts' own prompts. New setups start autonomous; existing ones stay assisted until you choose. `aisac claude --autonomous` or `--assisted` (also for codex) picks it for one session. Your host files are never written; `aisac doctor` audits them read-only and reports plain-text secrets and risky allow rules by key path, never by value (hostConfig).",
162
+ );
150
163
  console.log(
151
164
  'Managed hosts: `aisac setup --host-claude managed` or `--host-codex managed` selects the signed Claude Code or Codex pin under the aisac state directory; `aisac claude --host managed` and `aisac codex --host managed` select it for one session. Installs use scripts off and never replace your global CLI, shell profile or host configuration. The managed copy shares your existing host login. `system` keeps the global binary; AISAC_HOST_MODE=system forces that choice for one launch. Doctor reports the selected mode and compatibility under `hosts`.',
152
165
  );
@@ -761,6 +774,31 @@ function withManagedHost(release, host) {
761
774
  : { ...release, hostCodex: managed };
762
775
  }
763
776
 
777
+ /**
778
+ * The autonomy profile question of an interactive setup (spec
779
+ * aisac-engineering-autonomy FR1). Enter keeps the default; anything unclear too.
780
+ * @param {'assisted' | 'autonomous'} fallback @param {'pt-BR' | 'en'} locale
781
+ * @returns {Promise<'assisted' | 'autonomous'>}
782
+ */
783
+ async function askSetupProfile(fallback, locale) {
784
+ const rl = createInterface({ input: stdin, output: stdout });
785
+ const choice = fallback === 'autonomous' ? '2' : '1';
786
+ const question =
787
+ locale === 'pt-BR'
788
+ ? `\nPerfil das sessões do aisac:\n 1) assisted: os hosts perguntam como hoje\n 2) autonomous: menos perguntas (modo auto, lista de bloqueios e todos os guardrails)\nEscolha 1 ou 2 [${choice}]: `
789
+ : `\nProfile of aisac sessions:\n 1) assisted: the hosts ask you as they do today\n 2) autonomous: fewer prompts (auto mode, the deny baseline and every guardrail)\nChoose 1 or 2 [${choice}]: `;
790
+ try {
791
+ const answer = (await rl.question(question)).trim().toLowerCase();
792
+ if (answer === '1' || answer === 'assisted') return 'assisted';
793
+ if (answer === '2' || answer === 'autonomous') return 'autonomous';
794
+ return fallback;
795
+ } catch {
796
+ return fallback;
797
+ } finally {
798
+ rl.close();
799
+ }
800
+ }
801
+
764
802
  /**
765
803
  * The one question offering the signed private copy of an incompatible host (C8).
766
804
  * @param {'claude' | 'codex'} host @param {{ version: string | null, reason: string }} compatibility
@@ -876,6 +914,7 @@ async function setup(args) {
876
914
  '--channel',
877
915
  '--host-claude',
878
916
  '--host-codex',
917
+ '--profile',
879
918
  ]),
880
919
  new Set([
881
920
  '--client',
@@ -892,6 +931,7 @@ async function setup(args) {
892
931
  '--channel',
893
932
  '--host-claude',
894
933
  '--host-codex',
934
+ '--profile',
895
935
  ]),
896
936
  );
897
937
  if (args.includes('--login')) {
@@ -905,7 +945,26 @@ async function setup(args) {
905
945
  const lang = option(args, '--lang');
906
946
  if (lang !== undefined && !isPackLocale(lang)) throw new Error('invalid_lang');
907
947
  let release = requestedReleaseSettings(args);
948
+ const profileOption = option(args, '--profile');
949
+ if (profileOption !== undefined && !isAutonomyProfile(profileOption))
950
+ throw Object.assign(new Error('profile_invalid'), {
951
+ guide: describeProfileError(
952
+ 'profile_invalid',
953
+ resolvePackLocale(await readStoredLocale(stateRoot()), process.env),
954
+ ),
955
+ exitCode: 2,
956
+ });
908
957
  const previous = await readConfig();
958
+ // `--profile` alone changes only the autonomy profile of an existing setup, offline
959
+ // (spec aisac-engineering-autonomy FR1).
960
+ if (profileOption !== undefined && args.length === 2 && previous !== null) {
961
+ const root = await ensureStateRoot();
962
+ await writeStoredProfile(root, profileOption);
963
+ console.log(
964
+ profileSetLine(profileOption, root, resolvePackLocale(await readStoredLocale(root)), true),
965
+ );
966
+ return;
967
+ }
909
968
  // `--lang` alone only switches the language of an existing setup. Before the first
910
969
  // setup it runs the full setup (token included) and stores the language at the end.
911
970
  if (lang !== undefined && args.length === 2 && previous !== null) return setPackLocale(lang);
@@ -983,6 +1042,15 @@ async function setup(args) {
983
1042
  // aisac-host-upgrade-resilience C7, C8): an incompatible host costs the user neither.
984
1043
  const preflight = await preflightSetupHosts(clients, release, locale);
985
1044
  release = preflight.release;
1045
+ // The profile (FR1, Q2): the flag, else one question at a terminal, else the stored
1046
+ // choice of an existing setup, else `autonomous` for a first setup. Stored at the end.
1047
+ const storedProfile = await readStoredProfile(stateRoot());
1048
+ const profileDefault = storedProfile ?? (previous === null ? NEW_SETUP_PROFILE : null);
1049
+ const chosenProfile =
1050
+ profileOption ??
1051
+ (stdin.isTTY === true && stdout.isTTY === true
1052
+ ? await askSetupProfile(profileDefault ?? 'assisted', locale)
1053
+ : profileDefault);
986
1054
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
987
1055
  validateEndpoint(endpoint);
988
1056
  const selection = selectedPolicy(args, previous, clients);
@@ -1158,6 +1226,10 @@ async function setup(args) {
1158
1226
  `Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
1159
1227
  );
1160
1228
  await recordSetupConsent(root, locale, release);
1229
+ if (chosenProfile !== null) {
1230
+ await writeStoredProfile(root, chosenProfile);
1231
+ console.log(profileSetLine(chosenProfile, root, locale));
1232
+ }
1161
1233
  if (lang !== undefined) await setPackLocale(lang);
1162
1234
  // Display only: the server decides again on every pack request (ADR-0047).
1163
1235
  const line = licenseLine(await checkEngineeringLicense(endpoint, token));
@@ -1410,6 +1482,12 @@ async function doctor(json) {
1410
1482
  }).catch(() => null),
1411
1483
  // Machine resources (spec aisac-engineering-resources FR1): counts only, no worktree work.
1412
1484
  resources: await resourcesDoctorSection({ root: stateRoot() }).catch(() => null),
1485
+ // The autonomy profile (FR1) and the read-only audit of the user's host files (FR8).
1486
+ autonomy: resolveProfile({ flag: null, stored: await readStoredProfile(stateRoot()) }),
1487
+ hostConfig: await auditHostConfig({
1488
+ cwd: process.cwd(),
1489
+ locale: resolvePackLocale(await readStoredLocale(stateRoot()), process.env),
1490
+ }).catch(() => null),
1413
1491
  paidOrPilot: probe?.ok
1414
1492
  ? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
1415
1493
  : config
@@ -1422,6 +1500,7 @@ async function doctor(json) {
1422
1500
  for (const line of releaseDoctorLines(result)) console.log(line);
1423
1501
  console.log(managerDoctorLine(result.manager));
1424
1502
  console.log(resourcesDoctorLine(result.resources));
1503
+ for (const line of hostConfigDoctorLines(result.hostConfig)) console.log(line);
1425
1504
  }
1426
1505
  if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
1427
1506
  }
@@ -1551,6 +1630,8 @@ async function status(json) {
1551
1630
  // Host modes as stored (FR8); whether the managed copy is installed is doctor's.
1552
1631
  hosts: { claude: releaseSettings.hosts.claude, codex: releaseSettings.hosts.codex },
1553
1632
  extensions: await extensionsSummary(stateRoot()),
1633
+ // The autonomy profile and its source (spec aisac-engineering-autonomy FR1).
1634
+ autonomy: resolveProfile({ flag: null, stored: await readStoredProfile(stateRoot()) }),
1554
1635
  monitoredSession: null,
1555
1636
  monitoringStatus: 'not_observed',
1556
1637
  };
@@ -1743,14 +1824,24 @@ async function main(argv) {
1743
1824
  // `--manager`, `--worker <name>` and `--room <name>` belong to the launcher as
1744
1825
  // well (spec aisac-engineering-manager D2): a manager is a Claude Code session,
1745
1826
  // a worker a Codex session.
1827
+ // `--autonomous` / `--assisted` belong to the launcher too (spec
1828
+ // aisac-engineering-autonomy FR1); Codex owns `--profile`.
1829
+ let autonomyFlag;
1830
+ try {
1831
+ autonomyFlag = takeProfileFlag(launch.args);
1832
+ } catch (error) {
1833
+ const guide = describeProfileError(errorMessage(error), locale);
1834
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1835
+ throw error;
1836
+ }
1746
1837
  let role;
1747
1838
  try {
1748
- role = takeRoleFlags(launch.args, command);
1839
+ role = takeRoleFlags(autonomyFlag.args, command);
1749
1840
  } catch (error) {
1750
1841
  const code = error instanceof Error ? error.message : String(error);
1751
1842
  const guide =
1752
- describeRoleError(code, launch.args, command, locale) ??
1753
- describePermissionError(error, launch.args, locale);
1843
+ describeRoleError(code, autonomyFlag.args, command, locale) ??
1844
+ describePermissionError(error, autonomyFlag.args, locale);
1754
1845
  if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1755
1846
  throw error;
1756
1847
  }
@@ -1797,6 +1888,7 @@ async function main(argv) {
1797
1888
  {
1798
1889
  hostMode: launch.hostMode,
1799
1890
  role: role.request,
1891
+ autonomy: autonomyFlag.profile,
1800
1892
  },
1801
1893
  )
1802
1894
  : launchCodex(
@@ -1804,7 +1896,7 @@ async function main(argv) {
1804
1896
  root,
1805
1897
  nativeArgs,
1806
1898
  {},
1807
- { hostMode: launch.hostMode, role: role.request },
1899
+ { hostMode: launch.hostMode, role: role.request, autonomy: autonomyFlag.profile },
1808
1900
  ));
1809
1901
  process.exitCode = result;
1810
1902
  return;
@@ -205,7 +205,7 @@ export function resolvePackLocale(stored, env = process.env) {
205
205
  * @param {string} path
206
206
  * @returns {Promise<unknown>}
207
207
  */
208
- async function readSmallStateJson(path) {
208
+ export async function readSmallStateJson(path) {
209
209
  let handle;
210
210
  try {
211
211
  const link = await lstat(path);