@brunobracaioli/aibrain 0.4.0-beta.31 → 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.
@@ -534,6 +534,10 @@ async function main() {
534
534
  };
535
535
  process.once('SIGINT', shutdown);
536
536
  process.once('SIGTERM', shutdown);
537
+ // Closing the terminal sends SIGHUP (the kernel to the foreground group, and the
538
+ // launcher forwards it). Without a handler Node exits at once, skipping cleanup and
539
+ // leaving the detached monitor group (monitor, compaction proxy, app-server) running.
540
+ process.once('SIGHUP', shutdown);
537
541
 
538
542
  initialGeneration = spawnMonitor();
539
543
 
@@ -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.31';
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']);