@agentpro/scroll 0.0.0-stage → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/AGENTS.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +293 -2
  4. package/SPEC.md +1079 -0
  5. package/bin/scroll.js +8 -0
  6. package/docs/prompt-caching.md +128 -0
  7. package/index.js +33 -0
  8. package/lib/audit.js +358 -0
  9. package/lib/auth.js +849 -0
  10. package/lib/chat-sdk/admin-controller.js +289 -0
  11. package/lib/chat-sdk/debouncer.js +94 -0
  12. package/lib/chat-sdk/group-grants.js +150 -0
  13. package/lib/chat-sdk/index.js +222 -0
  14. package/lib/chat-sdk/long-task-runner.js +413 -0
  15. package/lib/chat-session.js +1788 -0
  16. package/lib/chat-telemetry.js +557 -0
  17. package/lib/codex-app-server.js +851 -0
  18. package/lib/digest.js +112 -0
  19. package/lib/effects.js +157 -0
  20. package/lib/eval.js +408 -0
  21. package/lib/grounding.js +356 -0
  22. package/lib/installers.js +176 -0
  23. package/lib/knowledge.js +335 -0
  24. package/lib/ledger.js +38 -0
  25. package/lib/loop.js +197 -0
  26. package/lib/mcp-client.js +926 -0
  27. package/lib/memory-cli.js +66 -0
  28. package/lib/memory-tracker.js +1472 -0
  29. package/lib/memory.js +1279 -0
  30. package/lib/people-cli.js +81 -0
  31. package/lib/people.js +534 -0
  32. package/lib/permissions.js +272 -0
  33. package/lib/providers.js +1572 -0
  34. package/lib/runtime.js +928 -0
  35. package/lib/sandbox.js +744 -0
  36. package/lib/scheduler.js +402 -0
  37. package/lib/scroll.js +1225 -0
  38. package/lib/skill-cli.js +120 -0
  39. package/lib/skill-eval.js +156 -0
  40. package/lib/skills.js +860 -0
  41. package/lib/style.js +126 -0
  42. package/lib/tool-retriever.js +489 -0
  43. package/lib/tools.js +1833 -0
  44. package/lib/user.js +711 -0
  45. package/lib/vault.js +151 -0
  46. package/package.json +88 -4
  47. package/templates/agent/IDENTITY.md +56 -0
  48. package/templates/agent/SOUL.md +23 -0
  49. package/templates/agent/TOOLS.md +25 -0
  50. package/templates/agent/evals/case-02-citation-discipline.md +29 -0
  51. package/templates/agent/evals/case-03-boundary.md +27 -0
  52. package/templates/agent/evals/case-example.md +43 -0
  53. package/templates/agent/hard-rules.md +11 -0
  54. package/templates/agent/memory/lessons.md +5 -0
  55. package/templates/agent/memory/log/.gitkeep +0 -0
  56. package/templates/external-safety-contract.md +5 -0
  57. package/templates/long-task-planner.md +17 -0
  58. package/templates/work/LOOP.md +37 -0
  59. package/templates/work/WORK.md +50 -0
  60. package/types/chat.d.ts +61 -0
  61. package/types/index.d.ts +112 -0
package/lib/user.js ADDED
@@ -0,0 +1,711 @@
1
+ // SCROLL — deployment USER.md (spec v1.9: §38 single USER.md · §39 role binding & neutral prompt
2
+ // header · §40 authority check via people.js · §41 privacy, guard, hash audit, workspace import).
3
+ //
4
+ // One file per deployment (`USER.md`), living OUTSIDE `agents/`. Frontmatter is machine-only and
5
+ // never enters the prompt. Body is capped (default 3,000 chars) and rendered under a neutral
6
+ // header ("The party this agent works for", never the word "user") so models do not confuse an
7
+ // external chat counterparty with the principal.
8
+ //
9
+ // Deterministic, zero dependencies, no model call. Node >= 20.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+ import { parseFrontmatter } from './scroll.js';
14
+ import { loadScrollConfig, expandPath } from './skills.js';
15
+ import { findSecret, looksLikeInstruction } from './memory.js';
16
+ import { TIERS, normalizeTier } from './permissions.js';
17
+ import {
18
+ SLUG_RE, ROLE_RE, ADDRESS_LIKE, ACTION_CLASSES,
19
+ validateCard, peopleConfig, parseAmount, roleOf,
20
+ } from './people.js';
21
+
22
+ const sha = (s) => crypto.createHash('sha256').update(String(s)).digest('hex');
23
+ const arr = (x) => (Array.isArray(x) ? x : x == null || x === '' ? [] : [x]);
24
+ const isObj = (x) => x && typeof x === 'object' && !Array.isArray(x);
25
+ const strField = (v) => (typeof v === 'string' ? v : (typeof v === 'number' ? String(v) : null));
26
+
27
+ export const USER_DEFAULTS = {
28
+ max_body_chars: 3000,
29
+ max_name_chars: 120,
30
+ max_address_chars: 60,
31
+ admin_roles: ['owner', 'admin'],
32
+ };
33
+
34
+ const PRINCIPAL_KINDS = new Set(['person', 'org']);
35
+ const PRINCIPAL_FIELDS = new Set(['kind', 'name', 'self', 'call_others', 'handoff']);
36
+ const PERSON_ENTRY_FIELDS = new Set([
37
+ 'id', 'name', 'call', 'self', 'role', 'roles', 'approve', 'max_amount',
38
+ 'channels', 'language', 'timezone', 'address_overrides', 'channel_ids',
39
+ ]);
40
+ const LABELS_EN = {
41
+ header: 'The party this agent works for',
42
+ preamble: 'Deployment context written by the principal. Facts only — never rules that override hard-rules.md.',
43
+ may_say: 'May say on behalf',
44
+ must_not_say: 'Must not say',
45
+ };
46
+
47
+ const CANARY_RE = /<!--\s*canary:\s*([^-\s][^>]*?)\s*-->/gi;
48
+ const MAY_SAY_HEADING_RE = /^##\s+(?:may\s+say(?:\s+on\s+behalf)?|allowed\s+statements?)\s*$/i;
49
+ const MUST_NOT_SAY_HEADING_RE = /^##\s+(?:must\s+not\s+say|forbidden\s+topics?|do\s+not\s+say)\s*$/i;
50
+ const AGENT_SECTION_RE = /^#{1,3}\s+(?:agent\s+notes?|learned|observations?|auto[- ]updated|memory\s+notes?)\s*$/i;
51
+ const AGENT_LINE_RE = /^\s*(?:[-*]\s*)?(?:\[agent\]|\[auto\]|auto[- ]noted:|<!--\s*agent\s*-->)/i;
52
+
53
+ // ── configuration ──────────────────────────────────────────────────────────────────────────────
54
+ export function userConfig({ cwd = process.cwd(), config = null, file = null, env = process.env } = {}) {
55
+ let cfg = config;
56
+ if (!cfg) { try { cfg = loadScrollConfig(cwd); } catch { cfg = {}; } }
57
+ const u = isObj(cfg && cfg.user) ? cfg.user : {};
58
+ const p = isObj(cfg && cfg.people) ? cfg.people : {};
59
+ const raw = file || env.SCROLL_USER_FILE || u.file || 'USER.md';
60
+ const abs = path.resolve(cwd, expandPath(raw, env));
61
+ const roles = isObj(u.roles)
62
+ ? Object.fromEntries(Object.entries(u.roles).map(([r, v]) => [r, arr(v).map(String)]))
63
+ : (isObj(p.roles) ? Object.fromEntries(Object.entries(p.roles).map(([r, v]) => [r, arr(v).map(String)])) : null);
64
+ return {
65
+ file: abs,
66
+ roles,
67
+ admin_roles: arr(u.admin_roles).length ? arr(u.admin_roles).map(String) : USER_DEFAULTS.admin_roles,
68
+ max_body_chars: Number(u.max_body_chars) > 0 ? Number(u.max_body_chars) : USER_DEFAULTS.max_body_chars,
69
+ action_classes: {
70
+ ...ACTION_CLASSES,
71
+ ...(isObj(p.action_classes) ? p.action_classes : {}),
72
+ ...(isObj(u.action_classes) ? u.action_classes : {}),
73
+ },
74
+ ceiling: isObj(u.authority_ceiling) ? u.authority_ceiling : (isObj(p.authority_ceiling) ? p.authority_ceiling : null),
75
+ labels: { ...LABELS_EN, ...(isObj(u.labels) ? u.labels : {}) },
76
+ tracked: u.tracked === true,
77
+ canaries: arr(u.canaries).map(String).filter(Boolean),
78
+ cwd,
79
+ };
80
+ }
81
+
82
+ // ── parse USER.md into frontmatter, structured body sections, and explicit canaries ────────────
83
+ export function parseUserMd(raw) {
84
+ const text = String(raw ?? '').replace(/\r\n?/g, '\n');
85
+ const canaries = [];
86
+ for (const m of text.matchAll(CANARY_RE)) {
87
+ const tok = m[1].trim();
88
+ if (tok) canaries.push(tok);
89
+ }
90
+ let frontmatter = null;
91
+ let body = '';
92
+ let error = null;
93
+ try {
94
+ const p = parseFrontmatter(text);
95
+ frontmatter = p.frontmatter;
96
+ body = String(p.body || '').trim();
97
+ } catch (e) {
98
+ error = e.message;
99
+ }
100
+ const cleanBody = body.replace(CANARY_RE, '').trim();
101
+ const sections = splitUserSections(cleanBody);
102
+ return { frontmatter, body: cleanBody, rawBody: body, sections, canaries, error };
103
+ }
104
+
105
+ export function splitUserSections(body) {
106
+ const lines = String(body ?? '').split('\n');
107
+ const buckets = { about: [], maySay: [], mustNotSay: [] };
108
+ let cur = 'about';
109
+ for (const line of lines) {
110
+ if (MAY_SAY_HEADING_RE.test(line.trim())) { cur = 'maySay'; continue; }
111
+ if (MUST_NOT_SAY_HEADING_RE.test(line.trim())) { cur = 'mustNotSay'; continue; }
112
+ if (/^##\s+/.test(line.trim()) && cur !== 'about') { cur = 'about'; }
113
+ buckets[cur].push(line);
114
+ }
115
+ return {
116
+ about: buckets.about.join('\n').trim(),
117
+ maySay: buckets.maySay.join('\n').trim(),
118
+ mustNotSay: buckets.mustNotSay.join('\n').trim(),
119
+ };
120
+ }
121
+
122
+ function collectStrings(v, out = []) {
123
+ if (typeof v === 'string') out.push(v);
124
+ else if (Array.isArray(v)) v.forEach((x) => collectStrings(x, out));
125
+ else if (isObj(v)) Object.values(v).forEach((x) => collectStrings(x, out));
126
+ return out;
127
+ }
128
+
129
+ // Normalize one entry in USER.md `people: [...]` into the lib/people.js card shape
130
+ export function personEntryToCard(entry, principal = {}) {
131
+ const roles = [...new Set([...arr(entry.role), ...arr(entry.roles)].map(String).filter(Boolean))];
132
+ const callThem = strField(entry.call);
133
+ const selfRef = strField(entry.self) || strField(principal.self);
134
+ const address = (callThem || selfRef)
135
+ ? { ...(callThem ? { call_them: callThem } : {}), ...(selfRef ? { self: selfRef } : {}) }
136
+ : undefined;
137
+ const hasAuth = entry.approve !== undefined || entry.max_amount !== undefined;
138
+ const authority = hasAuth
139
+ ? {
140
+ ...(entry.approve !== undefined ? { approve: arr(entry.approve) } : {}),
141
+ ...(entry.max_amount !== undefined ? { max_amount: entry.max_amount } : {}),
142
+ }
143
+ : undefined;
144
+ const fm = {
145
+ slug: entry.id,
146
+ name: entry.name,
147
+ ...(address ? { address } : {}),
148
+ ...(entry.language !== undefined ? { language: entry.language } : {}),
149
+ ...(entry.timezone !== undefined ? { timezone: entry.timezone } : {}),
150
+ ...(roles.length ? { roles } : {}),
151
+ ...(authority ? { authority } : {}),
152
+ ...(entry.channels !== undefined ? { channels: arr(entry.channels) } : {}),
153
+ ...(entry.address_overrides !== undefined ? { address_overrides: entry.address_overrides } : {}),
154
+ };
155
+ return { fileSlug: typeof entry.id === 'string' ? entry.id : null, frontmatter: fm, body: '' };
156
+ }
157
+
158
+ // ── validate parsed USER.md (reuses validateCard from lib/people.js) ───────────────────────────
159
+ export function validateUserMd(parsed, cfg = userConfig({ config: {} })) {
160
+ const errors = [], warnings = [];
161
+ const fm = parsed.frontmatter;
162
+ if (!isObj(fm)) return { errors: [parsed.error || 'USER.md has no YAML frontmatter (--- ... ---)'], warnings, people: [] };
163
+
164
+ // principal block (required, exactly one)
165
+ const pr = fm.principal;
166
+ if (!isObj(pr)) {
167
+ errors.push('missing required frontmatter map "principal" ({ kind, name, ... })');
168
+ } else {
169
+ if (!pr.kind || !PRINCIPAL_KINDS.has(String(pr.kind))) {
170
+ errors.push(`principal.kind "${pr.kind ?? ''}" must be "person" or "org"`);
171
+ }
172
+ if (typeof pr.name !== 'string' || !pr.name.trim()) {
173
+ errors.push('principal.name is required');
174
+ } else if (pr.name.length > USER_DEFAULTS.max_name_chars) {
175
+ errors.push(`principal.name is longer than ${USER_DEFAULTS.max_name_chars} characters`);
176
+ }
177
+ for (const k of ['self', 'call_others']) {
178
+ if (pr[k] !== undefined) {
179
+ const s = strField(pr[k]);
180
+ if (s == null || !s.trim()) errors.push(`principal.${k} must be a non-empty string`);
181
+ else if (s.length > USER_DEFAULTS.max_address_chars) errors.push(`principal.${k} is longer than ${USER_DEFAULTS.max_address_chars} characters`);
182
+ }
183
+ }
184
+ if (pr.handoff !== undefined && !ROLE_RE.test(String(pr.handoff))) {
185
+ errors.push(`principal.handoff "${pr.handoff}" must be a valid role name`);
186
+ }
187
+ for (const k of Object.keys(pr)) {
188
+ if (!PRINCIPAL_FIELDS.has(k)) warnings.push(`principal.${k} is not a known field`);
189
+ }
190
+ }
191
+
192
+ // people list (internal team/principal members only — validated via validateCard)
193
+ const peopleCfg = peopleConfig({
194
+ cwd: cfg.cwd,
195
+ config: { people: { action_classes: cfg.action_classes, max_body_chars: cfg.max_body_chars } },
196
+ });
197
+ const validatedPeople = [];
198
+ if (fm.people !== undefined && !Array.isArray(fm.people)) {
199
+ errors.push('people must be a list of internal team members');
200
+ } else {
201
+ const seenIds = new Set();
202
+ for (let i = 0; i < arr(fm.people).length; i++) {
203
+ const entry = fm.people[i];
204
+ if (!isObj(entry)) { errors.push(`people[${i}] must be a map`); continue; }
205
+ const rawId = entry.id == null ? '' : String(entry.id);
206
+ if (!rawId) {
207
+ errors.push(`people[${i}]: missing required field "id"`);
208
+ } else if (ADDRESS_LIKE.test(rawId)) {
209
+ errors.push(`people[${i}].id "${rawId.slice(0, 4)}..." looks like a phone number, email or address — use a stable slug id; map channel ids in the app`);
210
+ } else if (!SLUG_RE.test(rawId)) {
211
+ errors.push(`people[${i}].id "${rawId}" must match ^[a-z][a-z0-9-]*$`);
212
+ } else if (seenIds.has(rawId)) {
213
+ errors.push(`people[${i}].id "${rawId}" is duplicated`);
214
+ } else {
215
+ seenIds.add(rawId);
216
+ }
217
+ for (const k of Object.keys(entry)) {
218
+ if (!PERSON_ENTRY_FIELDS.has(k)) warnings.push(`people[${rawId || i}].${k} is not a known field`);
219
+ }
220
+ const card = personEntryToCard(entry, isObj(pr) ? pr : {});
221
+ const v = validateCard(card, peopleCfg);
222
+ for (const e of v.errors) {
223
+ if (e.includes('slug') && (!rawId || !SLUG_RE.test(rawId))) continue; // already reported as id
224
+ errors.push(`people[${rawId || i}]: ${e}`);
225
+ }
226
+ for (const w of v.warnings) warnings.push(`people[${rawId || i}]: ${w}`);
227
+ validatedPeople.push({
228
+ id: rawId,
229
+ slug: rawId,
230
+ entry,
231
+ frontmatter: card.frontmatter,
232
+ channelIds: arr(entry.channel_ids).map(String).filter(Boolean),
233
+ valid: v.errors.length === 0 && SLUG_RE.test(rawId) && !ADDRESS_LIKE.test(rawId),
234
+ });
235
+ }
236
+ }
237
+
238
+ for (const k of Object.keys(fm)) {
239
+ if (!['principal', 'people'].includes(k)) warnings.push(`unknown frontmatter field "${k}"`);
240
+ }
241
+
242
+ // body cap + secret & instruction-injection checks
243
+ const body = String(parsed.body || '');
244
+ if (body.length > cfg.max_body_chars) {
245
+ errors.push(`body is ${body.length} characters; the cap is ${cfg.max_body_chars} (user.max_body_chars) — keep detail in subject memory`);
246
+ }
247
+ const texts = [body, ...collectStrings(fm)];
248
+ if (texts.some((t) => findSecret(t))) {
249
+ errors.push('USER.md contains a secret (key, token, password, card number) — never store secrets in USER.md');
250
+ }
251
+ if (looksLikeInstruction(body)) {
252
+ errors.push('USER.md body reads as an instruction to agents (ignore rules, skip approvals, elevate privileges) — rules belong in hard-rules.md');
253
+ }
254
+ return { errors, warnings, people: validatedPeople };
255
+ }
256
+
257
+ // ── open deployment USER.md (frozen snapshot, wraps people.js authority rules) ─────────────────
258
+ export function openUser(opts = {}) {
259
+ const cfg = opts.cfg || userConfig(opts);
260
+ const exists = fs.existsSync(cfg.file) && fs.statSync(cfg.file).isFile();
261
+ let raw = '';
262
+ let hash = null;
263
+ let parsed = { frontmatter: null, body: '', rawBody: '', sections: { about: '', maySay: '', mustNotSay: '' }, canaries: [], error: null };
264
+ let validation = { errors: [], warnings: [], people: [] };
265
+ if (exists) {
266
+ raw = fs.readFileSync(cfg.file, 'utf8');
267
+ hash = sha(raw).slice(0, 16);
268
+ parsed = parseUserMd(raw);
269
+ validation = validateUserMd(parsed, cfg);
270
+ }
271
+ const valid = exists && validation.errors.length === 0;
272
+ const principal = valid && isObj(parsed.frontmatter?.principal) ? parsed.frontmatter.principal : null;
273
+ const cards = new Map();
274
+ if (valid) {
275
+ for (const p of validation.people) {
276
+ if (p.id) cards.set(p.id, { ...p, body: '', hash, errors: [], warnings: [] });
277
+ }
278
+ }
279
+
280
+ const getValid = (id) => { const c = cards.get(id); return c && c.valid ? c : null; };
281
+ function rolesOf(id) {
282
+ const c = getValid(id); if (!c) return [];
283
+ if (cfg.roles) return Object.keys(cfg.roles).filter((r) => cfg.roles[r].includes(id)).sort();
284
+ return arr(c.frontmatter.roles).map(String).sort();
285
+ }
286
+ function membersOf(role) {
287
+ const r = roleOf(role); if (!r) return [];
288
+ return [...cards.keys()].filter((s) => getValid(s) && rolesOf(s).includes(r)).sort();
289
+ }
290
+ function resolve(ref) {
291
+ const s = String(ref ?? '').trim();
292
+ if (s.startsWith('person:')) return getValid(s.slice(7)) ? [s.slice(7)] : [];
293
+ return membersOf(s);
294
+ }
295
+ const classTier = (c) => normalizeTier(cfg.action_classes[c]);
296
+ const classesOfTier = (tier) => Object.keys(cfg.action_classes).filter((c) => classTier(c) === tier).sort();
297
+ const covers = (list, { tier, action }) => {
298
+ const A = new Set(arr(list).map(String));
299
+ if (A.has(tier)) return true;
300
+ if (action) return A.has(action) && classTier(action) === tier;
301
+ const cls = classesOfTier(tier);
302
+ return cls.length > 0 && cls.every((c) => A.has(c));
303
+ };
304
+ function authorityOf(id) {
305
+ const c = getValid(id); if (!c) return { approve: [], max_amount: null };
306
+ const a = isObj(c.frontmatter.authority) ? c.frontmatter.authority : {};
307
+ let approve = arr(a.approve).map(String);
308
+ let max = typeof a.max_amount === 'number' ? a.max_amount : null;
309
+ if (cfg.ceiling) {
310
+ const ceil = rolesOf(id).map((r) => cfg.ceiling[r]).filter(isObj);
311
+ const allowed = ceil.flatMap((x) => arr(x.approve).map(String));
312
+ approve = approve.filter((e) => allowed.includes(e) || (classTier(e) && allowed.includes(classTier(e))));
313
+ const caps = ceil.map((x) => (typeof x.max_amount === 'number' ? x.max_amount : Infinity));
314
+ const ceilMax = caps.length ? Math.max(...caps) : 0;
315
+ if (Number.isFinite(ceilMax)) max = max == null ? ceilMax : Math.min(max, ceilMax);
316
+ }
317
+ return { approve: [...new Set(approve)].sort(), max_amount: max };
318
+ }
319
+ // Map a verified channel sender id (e.g. "zalo:12345", "telegram:99", "tg:99", or bare numeric id
320
+ // when unambiguously matched by a card's `channel_ids`) -> card.
321
+ function findByChannelId(channelId) {
322
+ if (!valid || !channelId) return null;
323
+ const target = String(channelId).trim();
324
+ if (!target) return null;
325
+ for (const c of cards.values()) {
326
+ if (c.channelIds.includes(target)) return c;
327
+ }
328
+ // Support bare numeric/platform id matching `<channel>:<id>` unambiguously
329
+ const stripped = target.replace(/^[a-z0-9_-]+:/i, '');
330
+ if (stripped) {
331
+ const matches = [];
332
+ for (const c of cards.values()) {
333
+ if (c.channelIds.some((cid) => cid === stripped || cid.endsWith(`:${stripped}`))) {
334
+ matches.push(c);
335
+ }
336
+ }
337
+ if (matches.length === 1) return matches[0];
338
+ }
339
+ return null;
340
+ }
341
+
342
+ function resolveApproverSlug(rawId) {
343
+ const s = String(rawId || '').trim();
344
+ if (!s) return null;
345
+ if (SLUG_RE.test(s) && cards.has(s)) return s;
346
+ const byCh = findByChannelId(s);
347
+ if (byCh && byCh.slug) return byCh.slug;
348
+ return null;
349
+ }
350
+
351
+ function canApprove(id, { tier, action = null, amount = null } = {}) {
352
+ const raw = String(id || '').trim();
353
+ if (!raw) return { ok: false, reason: 'unattributed' };
354
+ const resolvedSlug = resolveApproverSlug(raw);
355
+ if (!resolvedSlug) {
356
+ if (!SLUG_RE.test(raw)) return { ok: false, reason: 'unattributed' };
357
+ return { ok: false, reason: 'unknown_person' };
358
+ }
359
+ const c = cards.get(resolvedSlug);
360
+ if (!c) return { ok: false, reason: 'unknown_person' };
361
+ if (!c.valid) return { ok: false, reason: 'invalid_card' };
362
+ const t = normalizeTier(tier) || 'destructive';
363
+ if (action && !Object.prototype.hasOwnProperty.call(cfg.action_classes, action)) return { ok: false, reason: 'unknown_action' };
364
+ const au = authorityOf(resolvedSlug);
365
+ if (!covers(au.approve, { tier: t, action })) return { ok: false, reason: 'no_authority', tier: t, action };
366
+ if (au.max_amount != null) {
367
+ const amt = parseAmount(amount);
368
+ if (amt == null && t === 'financial') return { ok: false, reason: 'amount_unknown' };
369
+ if (amt != null && amt > au.max_amount) return { ok: false, reason: 'over_limit', amount: amt, max_amount: au.max_amount };
370
+ }
371
+ return { ok: true, slug: resolvedSlug };
372
+ }
373
+ const approversFor = (gate) => [...cards.keys()].filter((s) => getValid(s) && canApprove(s, gate).ok).sort();
374
+ function isInternal({ senderId = null, channelId = null, channelMap = null } = {}) {
375
+ if (!valid) return { internal: false, person: null, reason: 'no_user_md' };
376
+ // Verified channel mapping takes precedence over raw claims
377
+ if (channelId) {
378
+ const ch = String(channelId).trim();
379
+ if (isObj(channelMap) && channelMap[ch]) {
380
+ const mapped = getValid(String(channelMap[ch]));
381
+ if (mapped) return { internal: true, person: mapped, via: 'channel_map' };
382
+ return { internal: false, person: null, reason: 'unmatched_channel_map' };
383
+ }
384
+ const byCh = findByChannelId(ch);
385
+ if (byCh) return { internal: true, person: byCh, via: 'channel_ids' };
386
+ return { internal: false, person: null, reason: 'unknown_channel_id' };
387
+ }
388
+ if (senderId) {
389
+ const p = getValid(String(senderId).trim());
390
+ if (p) return { internal: true, person: p, via: 'verified_sender_id' };
391
+ return { internal: false, person: null, reason: 'unknown_sender_id' };
392
+ }
393
+ return { internal: false, person: null, reason: 'missing_sender' };
394
+ }
395
+
396
+ // Render prompt block: frontmatter NEVER enters the prompt; header NEVER uses the word "user"
397
+ function render({ audience = 'internal' } = {}) {
398
+ if (!valid) return { text: '', hash: null, chars: 0, audience };
399
+ const L = cfg.labels;
400
+ const parts = [];
401
+ if (audience === 'internal') {
402
+ if (parsed.sections.about) parts.push(parsed.sections.about);
403
+ }
404
+ if (parsed.sections.maySay) {
405
+ parts.push(`### ${L.may_say}\n${parsed.sections.maySay}`);
406
+ }
407
+ if (parsed.sections.mustNotSay) {
408
+ parts.push(`### ${L.must_not_say}\n${parsed.sections.mustNotSay}`);
409
+ }
410
+ if (!parts.length) return { text: '', hash, chars: 0, audience };
411
+ const inner = `## ${L.header}\n(${L.preamble})\n\n${parts.join('\n\n')}`;
412
+ const snap = sha(inner).slice(0, 16);
413
+ const text = `<principal snapshot="${snap}" audience="${audience}">\n${inner}\n</principal>`;
414
+ return { text, hash: snap, fileHash: hash, chars: text.length, audience };
415
+ }
416
+
417
+ // Tool-boundary guard: agents may never read/write USER.md directly (symlink & macOS case-safe)
418
+ function realpathCaseSafe(p) {
419
+ const abs = path.resolve(p);
420
+ try { return fs.realpathSync.native(abs); } catch {
421
+ try {
422
+ const parent = fs.realpathSync.native(path.dirname(abs));
423
+ return path.join(parent, path.basename(abs));
424
+ } catch {
425
+ return abs;
426
+ }
427
+ }
428
+ }
429
+
430
+ function guard(targetPath) {
431
+ const rp = path.resolve(targetPath);
432
+ if (rp === cfg.file) {
433
+ return { allowed: false, tier: 'destructive', reason: 'user_md_is_written_by_people' };
434
+ }
435
+ if (rp !== cfg.file) {
436
+ const realTarget = realpathCaseSafe(rp);
437
+ const realFile = realpathCaseSafe(cfg.file);
438
+ if (realTarget === realFile) {
439
+ return { allowed: false, tier: 'destructive', reason: 'user_md_is_written_by_people' };
440
+ }
441
+ if (path.dirname(realTarget).toLowerCase() === path.dirname(realFile).toLowerCase()
442
+ && path.basename(realTarget).toLowerCase() === path.basename(realFile).toLowerCase()) {
443
+ return { allowed: false, tier: 'destructive', reason: 'user_md_is_written_by_people' };
444
+ }
445
+ }
446
+ return { allowed: true };
447
+ }
448
+
449
+ // Per-run file hash audit: detects out-of-band USER.md edits between runs
450
+ function checkHashChange(stateDir) {
451
+ if (!exists || !hash) return { changed: false, previousHash: null, hash: null };
452
+ const marker = path.join(stateDir, 'user-md.hash.json');
453
+ let previousHash = null;
454
+ if (fs.existsSync(marker)) {
455
+ try { previousHash = JSON.parse(fs.readFileSync(marker, 'utf8')).hash || null; } catch { /* ignore */ }
456
+ }
457
+ fs.mkdirSync(stateDir, { recursive: true });
458
+ fs.writeFileSync(marker, JSON.stringify({ file: path.relative(cfg.cwd, cfg.file) || cfg.file, hash, updatedAt: new Date().toISOString() }, null, 2) + '\n');
459
+ return { changed: previousHash != null && previousHash !== hash, previousHash, hash };
460
+ }
461
+
462
+ function check({ agents = [] } = {}) {
463
+ const errors = [], warnings = [];
464
+ const rel = (p) => path.relative(cfg.cwd, p) || p;
465
+ const agentsDir = path.join(cfg.cwd, 'agents');
466
+ if (cfg.file.startsWith(agentsDir + path.sep)) {
467
+ errors.push(`${rel(cfg.file)} is inside agents/ — USER.md must live outside every agent folder (§41)`);
468
+ }
469
+ if (!exists) return { errors, warnings, active: false, people: 0 };
470
+ for (const e of validation.errors) errors.push(`${rel(cfg.file)}: ${e}`);
471
+ for (const w of validation.warnings) warnings.push(`${rel(cfg.file)}: ${w}`);
472
+ if (valid && principal && principal.handoff && cards.size > 0 && !membersOf(principal.handoff).length) {
473
+ warnings.push(`${rel(cfg.file)}: principal.handoff role "${principal.handoff}" has no matching member in people`);
474
+ }
475
+ for (const [c, t] of Object.entries(cfg.action_classes)) {
476
+ if (!TIERS.includes(String(t))) errors.push(`user.action_classes.${c}: "${t}" is not a §21 tier`);
477
+ }
478
+ for (const { name, identity } of agents) {
479
+ for (const r of arr(identity && identity.serves).map(roleOf).filter(Boolean)) {
480
+ if (valid && cards.size > 0 && !membersOf(r).length) {
481
+ warnings.push(`agent ${name} serves role "${r}", which nobody in USER.md holds`);
482
+ }
483
+ }
484
+ }
485
+ return { errors, warnings, active: valid, people: cards.size, hash };
486
+ }
487
+
488
+ const allCanaries = () => [...new Set([...parsed.canaries, ...cfg.canaries])];
489
+
490
+ return {
491
+ cfg, file: cfg.file, exists, valid, active: valid, hash,
492
+ principal, sections: parsed.sections, cards,
493
+ errors: validation.errors, warnings: validation.warnings,
494
+ get: (id) => cards.get(id) || null,
495
+ slugs: () => [...cards.keys()],
496
+ rolesOf, membersOf, resolve, authorityOf, canApprove, approversFor,
497
+ findByChannelId, isInternal, render, guard, checkHashChange, check,
498
+ maySayText: () => parsed.sections.maySay,
499
+ mustNotSayText: () => parsed.sections.mustNotSay,
500
+ canaries: allCanaries,
501
+ handoffRole: () => (principal && principal.handoff ? String(principal.handoff) : 'owner'),
502
+ };
503
+ }
504
+
505
+ // ── External workspace USER.md import (§38) ────────────────────────────────────────────────────
506
+ // Human-written prose becomes the USER.md body; agent-appended notes/observations are NEVER
507
+ // promoted into human-authored principal context — they route to the gated subject-memory queue.
508
+ export function importWorkspaceUserMd(raw, {
509
+ principalName = 'Principal',
510
+ kind = 'person',
511
+ self = 'I',
512
+ callOthers = 'you',
513
+ handoff = 'owner',
514
+ maxBodyChars = USER_DEFAULTS.max_body_chars,
515
+ memoryStore = null,
516
+ subjectRef = null,
517
+ by = 'import',
518
+ } = {}) {
519
+ const text = String(raw ?? '').replace(/\r\n?/g, '\n');
520
+ const p = parseFrontmatter(text);
521
+ const body = String(p.body || '').trim();
522
+ const lines = body.split('\n');
523
+ const humanLines = [];
524
+ const agentNotes = [];
525
+ let inAgentSection = false;
526
+ for (const line of lines) {
527
+ const trimmed = line.trim();
528
+ if (/^#{1,3}\s+/.test(trimmed)) {
529
+ inAgentSection = AGENT_SECTION_RE.test(trimmed);
530
+ if (!inAgentSection) humanLines.push(line);
531
+ continue;
532
+ }
533
+ if (inAgentSection || AGENT_LINE_RE.test(line)) {
534
+ const cleaned = trimmed.replace(/^[-*]\s*/, '').replace(AGENT_LINE_RE, '').trim();
535
+ if (cleaned) agentNotes.push(cleaned);
536
+ continue;
537
+ }
538
+ humanLines.push(line);
539
+ }
540
+ const humanBody = humanLines.join('\n').replace(/\n{3,}/g, '\n\n').trim().slice(0, maxBodyChars);
541
+ const userMd = [
542
+ '---',
543
+ 'principal:',
544
+ ` kind: ${PRINCIPAL_KINDS.has(kind) ? kind : 'person'}`,
545
+ ` name: ${JSON.stringify(principalName)}`,
546
+ ` self: ${JSON.stringify(self)}`,
547
+ ` call_others: ${JSON.stringify(callOthers)}`,
548
+ ` handoff: ${handoff}`,
549
+ 'people: []',
550
+ '---',
551
+ humanBody || `# About ${principalName}`,
552
+ '',
553
+ ].join('\n');
554
+
555
+ const queuedMemory = [];
556
+ if (memoryStore && subjectRef && agentNotes.length) {
557
+ let sid = memoryStore.resolve(subjectRef);
558
+ if (!sid) {
559
+ sid = memoryStore.createSubject({ kind: 'person', label: principalName });
560
+ memoryStore.link(subjectRef, sid);
561
+ }
562
+ const sess = memoryStore.openSession(sid, { surface: 'import' });
563
+ for (let i = 0; i < agentNotes.length; i++) {
564
+ const note = agentNotes[i];
565
+ const turn = memoryStore.appendTurn(sid, sess, { role: 'agent', speaker: by, text: note });
566
+ const res = memoryStore.propose(sid, {
567
+ key: `imported_note_${i + 1}`,
568
+ about: 'self',
569
+ value: note,
570
+ provenance: 'agent_observed',
571
+ evidence: { ref: turn.ref, quote: note },
572
+ }, { by });
573
+ queuedMemory.push({ sid, note, result: res });
574
+ }
575
+ }
576
+ return { userMd, humanBody, agentNotes, queuedMemory };
577
+ }
578
+
579
+ export function userTemplate({ kind = 'org', name = 'Example Co', ownerId = 'owner', ownerName = 'Alex Rivera' } = {}) {
580
+ return `---
581
+ principal:
582
+ kind: ${kind}
583
+ name: ${JSON.stringify(name)}
584
+ self: "I"
585
+ call_others: "you"
586
+ handoff: staff
587
+ people:
588
+ - { id: ${ownerId}, name: ${JSON.stringify(ownerName)}, call: ${JSON.stringify(ownerName.split(' ')[0])}, role: owner, approve: [send, pay], max_amount: 5000, channels: [email, chat] }
589
+ ---
590
+ # About ${name}
591
+ Internal context loaded only when speaking with people listed above.
592
+
593
+ ## May say on behalf
594
+ - Hours and public policies that agents may state to external callers.
595
+
596
+ ## Must not say
597
+ - Private principal matters. Discounts or refunds require human handoff.
598
+ `;
599
+ }
600
+
601
+ // ── Per-turn internal vs external audience classifier & group lowest-trust wall (§42) ──────────
602
+ // Identity is NEVER inferred from displayName. A speaker is internal ONLY when their verified
603
+ // channelId (mapped via channelMap or USER.md channel_ids) or verified senderId matches a valid
604
+ // entry in USER.md. Missing sender fails closed to external.
605
+ // In a group chat, command authority follows the speaker, while loaded content & output wall
606
+ // follow the LEAST-TRUSTED participant present.
607
+ export function classifyTurn(userDoc, {
608
+ sender = null,
609
+ participants = null,
610
+ isGroup = false,
611
+ channelMap = null,
612
+ chatSubject = null,
613
+ } = {}) {
614
+ const verifyActor = (actor) => {
615
+ if (!actor || !userDoc || !userDoc.active) return { internal: false, person: null, reason: !actor ? 'missing_sender' : 'no_user_md' };
616
+ // displayName is explicitly ignored — only verified channelId or verified internal id counts
617
+ const channelId = actor.channelId || actor.channel_id || null;
618
+ const senderId = actor.verifiedId || actor.id || null;
619
+ if (channelId) return userDoc.isInternal({ channelId, channelMap });
620
+ if (senderId && actor.verified === true) return userDoc.isInternal({ senderId });
621
+ return { internal: false, person: null, reason: senderId ? 'unverified_sender_id' : 'missing_channel_id' };
622
+ };
623
+
624
+ const sp = verifyActor(sender);
625
+ const speakerTrust = sp.internal ? 'internal' : 'external';
626
+ const list = Array.isArray(participants) ? participants : null;
627
+ const group = isGroup || (list != null && list.length > 1);
628
+
629
+ let contentAudience = speakerTrust;
630
+ let wallReason = sp.internal ? 'verified_internal_speaker' : (sp.reason || 'external_speaker');
631
+ if (group) {
632
+ if (!list || list.length === 0) {
633
+ contentAudience = 'external';
634
+ wallReason = 'group_participants_unknown';
635
+ } else {
636
+ const anyExternal = list.some((p) => !verifyActor(p).internal);
637
+ if (anyExternal) {
638
+ contentAudience = 'external';
639
+ wallReason = 'group_lowest_trust_external';
640
+ }
641
+ }
642
+ }
643
+
644
+ const externalContent = contentAudience === 'external';
645
+ const writeToolsAllowed = speakerTrust === 'internal' && !externalContent;
646
+
647
+ return {
648
+ speakerTrust,
649
+ contentAudience,
650
+ isGroup: group,
651
+ speakerId: sp.person ? sp.person.id : null,
652
+ speakerRoles: sp.person ? userDoc.rolesOf(sp.person.id) : [],
653
+ userSections: externalContent ? ['maySay', 'mustNotSay'] : ['about', 'maySay', 'mustNotSay'],
654
+ writeToolsAllowed,
655
+ toolPolicyOverride: writeToolsAllowed ? null : 'none',
656
+ memoryScope: externalContent ? 'chat_only' : 'principal_and_team',
657
+ chatSubject: chatSubject || null,
658
+ draftOnly: externalContent,
659
+ requireApproval: externalContent,
660
+ groundingRequired: externalContent,
661
+ aiDisclosureRequired: externalContent,
662
+ reason: wallReason,
663
+ };
664
+ }
665
+
666
+ // Normalize diacritics to ASCII so bilingual/international patterns match without raw non-ASCII literals
667
+ function foldAscii(text) {
668
+ return String(text ?? '')
669
+ .normalize('NFD')
670
+ .replace(/[\u0300-\u036f]/g, '')
671
+ .replace(/\u0111/g, 'd')
672
+ .replace(/\u0110/g, 'D')
673
+ .toLowerCase();
674
+ }
675
+
676
+ const IDENTITY_Q_PATTERNS = [
677
+ /\b(?:are|r)\s+you\s+(?:a\s+|an\s+)?(?:bot|ai|robot|machine|human|real\s+person|automated|assistant|chatgpt|llm)\b/,
678
+ /\b(?:is\s+this|am\s+i\s+(?:talking|speaking|chatting)\s+(?:to|with))\s+(?:a\s+|an\s+)?(?:bot|ai|robot|human|real\s+person|assistant|the\s+real)\b/,
679
+ /\b(?:bot|ai)\s+or\s+(?:a\s+)?(?:human|real\s+person)\b/,
680
+ /\b(?:human|real\s+person)\s+or\s+(?:a\s+|an\s+)?(?:bot|ai)\b/,
681
+ /\bor\s+(?:a\s+|an\s+)?(?:bot|ai|robot)\b/,
682
+ /\bis\s+this\s+really\b/,
683
+ /\bwho\s+is\s+actually\s+(?:typing|replying|answering)\b/,
684
+ /\b(?:co\s+phai|la)\s+(?:bot|ai|may|nguoi\s+that|tro\s+ly\s+ao|tu\s+dong)\b/,
685
+ /\b(?:bot|ai|tro\s+ly\s+ao|may)\s+hay\s+nguoi\b/,
686
+ /\bnguoi\s+that\s+hay\s+(?:bot|ai|tro\s+ly\s+ao|may)\b/,
687
+ ];
688
+
689
+ const AI_ACKNOWLEDGE_RE = /\b(?:ai|artificial\s+intelligence|ai\s+assistant|virtual\s+assistant|automated\s+assistant|bot|tro\s+ly\s+ai|tro\s+ly\s+ao)\b/;
690
+ const AI_DENIAL_RE = /\b(?:i\s+am\s+(?:a\s+)?(?:real\s+)?human|i\s+am\s+not\s+(?:a\s+|an\s+)?(?:bot|ai)|no,?\s*i(?:'m|\s+am)\s+not\s+(?:a\s+|an\s+)?(?:bot|ai)|khong\s+phai\s+(?:bot|ai)|la\s+nguoi\s+that)\b/;
691
+
692
+ export function isIdentityQuestion(text) {
693
+ const f = foldAscii(text);
694
+ return IDENTITY_Q_PATTERNS.some((re) => re.test(f));
695
+ }
696
+
697
+ export function checkAiDisclosure(replyText) {
698
+ const f = foldAscii(replyText);
699
+ if (AI_DENIAL_RE.test(f)) return { ok: false, reason: 'denied_ai_identity' };
700
+ if (!AI_ACKNOWLEDGE_RE.test(f)) return { ok: false, reason: 'missing_ai_disclosure' };
701
+ return { ok: true };
702
+ }
703
+
704
+ export function applyAiLabel(text, { label = '[AI Assistant]', speaksAs = 'self', approvedByHuman = false } = {}) {
705
+ const s = String(text ?? '').trim();
706
+ if (!s || approvedByHuman || speaksAs === 'owner') return s;
707
+ const tag = String(label || '').trim();
708
+ if (!tag) return s;
709
+ if (s.startsWith(tag) || s.endsWith(tag)) return s;
710
+ return `${tag} ${s}`;
711
+ }