advisers 0.3.2 → 0.4.1

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 (44) hide show
  1. package/README-zh.md +13 -14
  2. package/README.md +37 -23
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2302 -95
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/error-codes.js +516 -7
  11. package/lib/evidence.js +697 -113
  12. package/lib/kb-extract.js +626 -0
  13. package/lib/kb-facts.js +429 -0
  14. package/lib/kb-pages.js +1084 -0
  15. package/lib/kb.js +1036 -0
  16. package/lib/mail-errors.js +46 -0
  17. package/lib/mail-extract.js +351 -0
  18. package/lib/mail-imap.js +446 -0
  19. package/lib/mail-import.js +176 -0
  20. package/lib/mail-parse.js +223 -0
  21. package/lib/mail-store.js +731 -0
  22. package/lib/mail.js +506 -0
  23. package/lib/mcp-server.js +196 -10
  24. package/lib/notify.js +265 -7
  25. package/lib/policy/decision.js +315 -0
  26. package/lib/policy/egress.js +268 -0
  27. package/lib/policy/errors.js +71 -0
  28. package/lib/policy/index.js +99 -0
  29. package/lib/policy/rules.js +468 -0
  30. package/lib/policy/surfaces.js +141 -0
  31. package/lib/receipt-verify.js +199 -19
  32. package/lib/receivables.js +1653 -0
  33. package/lib/scheduler.js +453 -9
  34. package/lib/shell.js +1406 -0
  35. package/lib/source.js +98 -3
  36. package/lib/sqlite.js +366 -49
  37. package/lib/tos/index.js +2 -2
  38. package/lib/tos/manifest.json +6 -6
  39. package/lib/tos/privacy.zh-CN.md +33 -20
  40. package/lib/tos/safety.zh-CN.md +7 -6
  41. package/lib/tos/summary.zh-CN.md +3 -2
  42. package/lib/tos/terms.zh-CN.md +31 -16
  43. package/lib/urgency.js +467 -0
  44. package/package.json +4 -4
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Decision tokens (0.4 grant-lite) + intent/result audit orchestration.
3
+ *
4
+ * authorize(action, facts) runs evaluate(); on allow it issues a one-shot token
5
+ * bound to an effectDigest (surface/action/path/recipient/subject/provider/
6
+ * dataClass/record kind+secrecy), writes an audit intent row, and returns the
7
+ * token. runWithDecision(token, effect, fn) consumes the token (allow + digest
8
+ * match + unused + unexpired), executes fn and writes the audit result row.
9
+ *
10
+ * Threat model: this catches "a code path forgot to call the gate" and "a
11
+ * decision for A is reused to execute B". It does NOT defend against a
12
+ * same-user process that can rewrite the source or read process memory;
13
+ * docs/SECURITY.md #8 stays the honest statement. The token is in-process only
14
+ * (a Map); 0.5 may add HMAC/TTL persistence. Decision tokens are not secrets.
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ import { POLICY_CODES, PolicyError, policyError } from './errors.js'
19
+ import { EFFECT_DIGEST_FIELDS, canonicalJson, effectDigestOf, evaluate } from './rules.js'
20
+
21
+ /** Default token lifetime (milliseconds). */
22
+ export const DECISION_TOKEN_TTL_MS = 60_000
23
+
24
+ const tokens = new Map()
25
+
26
+ function isPlainObject(value) {
27
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
28
+ }
29
+
30
+ function nowMs(now) {
31
+ if (now === undefined || now === null) return Date.now()
32
+ if (now instanceof Date) return now.getTime()
33
+ const value = typeof now === 'number' ? now : Date.parse(String(now))
34
+ if (!Number.isFinite(value)) throw new TypeError('authorize/consumeDecision now must be a Date, epoch ms or ISO string')
35
+ return value
36
+ }
37
+
38
+ function isoAt(ms) {
39
+ return new Date(ms).toISOString()
40
+ }
41
+
42
+ /** JSON-ready decision metadata without the token (safe to print/audit). */
43
+ export function decisionView(decision) {
44
+ if (!isPlainObject(decision)) return null
45
+ return {
46
+ surface: decision.surface,
47
+ action: decision.action,
48
+ dataClass: decision.dataClass,
49
+ decision: decision.decision,
50
+ code: decision.code ?? null,
51
+ policyCode: decision.policyCode ?? null,
52
+ ruleIds: Array.isArray(decision.ruleIds) ? [...decision.ruleIds] : [],
53
+ obligations: Array.isArray(decision.obligations) ? [...decision.obligations] : [],
54
+ reason: decision.reason,
55
+ effectDigest: decision.effectDigest,
56
+ }
57
+ }
58
+
59
+ function auditEvent(input) {
60
+ const event = {
61
+ at: input.at,
62
+ actor: input.actor || 'local',
63
+ surface: input.surface,
64
+ action: input.action,
65
+ policyAction: input.policyAction,
66
+ phase: input.phase,
67
+ decision: input.decision,
68
+ allowed: input.decision === 'allow',
69
+ }
70
+ for (const key of ['code', 'policyCode', 'reason', 'decisionId', 'effectDigest']) {
71
+ if (input[key] !== undefined && input[key] !== null && input[key] !== '') event[key] = input[key]
72
+ }
73
+ if (Array.isArray(input.ruleIds) && input.ruleIds.length) event.ruleIds = [...input.ruleIds]
74
+ if (input.ok !== undefined) event.ok = input.ok === true
75
+ return event
76
+ }
77
+
78
+ /**
79
+ * Write one audit row through a caller-supplied synchronous callback.
80
+ * Returns true on success; a throw or an explicit {ok:false} is a failure
81
+ * (fail closed). The callback never receives content: no quotes, paths,
82
+ * recipients or titles, only the metadata above.
83
+ */
84
+ function writeAudit(audit, event) {
85
+ if (typeof audit !== 'function') return false
86
+ let result
87
+ try {
88
+ result = audit(event)
89
+ } catch {
90
+ return false
91
+ }
92
+ if (result && typeof result.then === 'function') return false
93
+ if (isPlainObject(result) && result.ok === false) return false
94
+ return true
95
+ }
96
+
97
+ function tokenRecordOf(token) {
98
+ if (!isPlainObject(token)) return null
99
+ const decisionId = typeof token.decisionId === 'string' ? token.decisionId : ''
100
+ const effectDigest = typeof token.effectDigest === 'string' ? token.effectDigest : ''
101
+ if (!decisionId || !effectDigest) return null
102
+ return {
103
+ decisionId,
104
+ effectDigest,
105
+ surface: typeof token.surface === 'string' ? token.surface : '',
106
+ action: typeof token.action === 'string' ? token.action : '',
107
+ expiresAt: typeof token.expiresAt === 'string' ? token.expiresAt : '',
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Authorize one action for one set of facts.
113
+ *
114
+ * - deny/confirm: returns the evaluate() result plus {authorized:false,
115
+ * decisionId:null, token:null}; a deny/confirm audit row is attempted when a
116
+ * callback is supplied but its failure cannot change the refusal;
117
+ * - allow: writes the intent audit row before returning. If the action has the
118
+ * audit.intent obligation and the callback is missing/throws, the call is
119
+ * refused with E_POLICY_AUDIT_UNAVAILABLE and no token is issued.
120
+ *
121
+ * @param {string} action canonical policy action
122
+ * @param {object} facts see lib/policy/rules.js evaluate()
123
+ * @param {{now?: Date|number|string, ttlMs?: number, audit?: Function}} [options]
124
+ * @returns {object} decision + {authorized, decisionId, token, expiresAt, auditWritten}
125
+ */
126
+ export function authorize(action, facts, options = {}) {
127
+ if (typeof action !== 'string' || !action.trim()) throw new TypeError('authorize(action, facts) requires a non-empty action')
128
+ if (!isPlainObject(facts)) throw new TypeError('authorize(action, facts) requires a facts object')
129
+ if (!isPlainObject(options)) throw new TypeError('authorize options must be an object')
130
+ const at = nowMs(options.now)
131
+ const ttl = options.ttlMs === undefined || options.ttlMs === null ? DECISION_TOKEN_TTL_MS : Number(options.ttlMs)
132
+ if (!Number.isFinite(ttl) || ttl <= 0) throw new TypeError('authorize ttlMs must be a positive number of milliseconds')
133
+ const audit = options.audit
134
+ const decision = evaluate({ ...facts, action })
135
+ const base = { ...decision, authorized: false, decisionId: null, token: null, expiresAt: null, auditWritten: false }
136
+
137
+ if (decision.decision !== 'allow') {
138
+ const wrote = writeAudit(
139
+ audit,
140
+ auditEvent({
141
+ at: isoAt(at),
142
+ actor: facts.actor,
143
+ surface: decision.surface,
144
+ action: decision.action,
145
+ policyAction: action,
146
+ phase: 'decision',
147
+ decision: decision.decision,
148
+ code: decision.code,
149
+ policyCode: decision.policyCode,
150
+ reason: decision.reason,
151
+ ruleIds: decision.ruleIds,
152
+ }),
153
+ )
154
+ return { ...base, auditWritten: wrote }
155
+ }
156
+
157
+ const decisionId = 'dec_' + randomUUID()
158
+ const expiresAt = isoAt(at + ttl)
159
+ const token = { decisionId, effectDigest: decision.effectDigest, surface: decision.surface, action: decision.action, expiresAt }
160
+ const requiresIntent = Array.isArray(decision.obligations) && decision.obligations.includes('audit.intent')
161
+ if (requiresIntent) {
162
+ const wrote = writeAudit(
163
+ audit,
164
+ auditEvent({
165
+ at: isoAt(at),
166
+ actor: facts.actor,
167
+ surface: decision.surface,
168
+ action: decision.action,
169
+ policyAction: action,
170
+ phase: 'intent',
171
+ decision: 'allow',
172
+ decisionId,
173
+ effectDigest: decision.effectDigest,
174
+ ruleIds: decision.ruleIds,
175
+ }),
176
+ )
177
+ if (!wrote) {
178
+ return {
179
+ ...base,
180
+ decision: 'deny',
181
+ code: POLICY_CODES.POLICY_AUDIT_UNAVAILABLE.code,
182
+ policyCode: 'POLICY_AUDIT_UNAVAILABLE',
183
+ ruleIds: [...decision.ruleIds, 'R-P04-07'],
184
+ obligations: [],
185
+ reason: 'the intent audit could not be written; refusing the side effect',
186
+ }
187
+ }
188
+ }
189
+ tokens.set(decisionId, {
190
+ decisionId,
191
+ effectDigest: decision.effectDigest,
192
+ surface: decision.surface,
193
+ action: decision.action,
194
+ expiresAt: at + ttl,
195
+ used: false,
196
+ requiresAudit: requiresIntent,
197
+ createdAt: at,
198
+ })
199
+ return { ...base, authorized: true, decisionId, token, expiresAt, auditWritten: requiresIntent }
200
+ }
201
+
202
+ function assertToken(token) {
203
+ const record = tokenRecordOf(token)
204
+ if (!record) throw policyError('POLICY_TOKEN_INVALID', 'the decision token is malformed')
205
+ const stored = tokens.get(record.decisionId)
206
+ if (!stored) throw policyError('POLICY_TOKEN_UNKNOWN', 'the decision token was not issued by this process')
207
+ if (stored.used) throw policyError('POLICY_TOKEN_REPLAY', 'the decision token was already consumed')
208
+ if (record.effectDigest !== stored.effectDigest || record.surface !== stored.surface || record.action !== stored.action) {
209
+ throw policyError('POLICY_TOKEN_INVALID', 'the decision token fields were modified after issue')
210
+ }
211
+ return stored
212
+ }
213
+
214
+ /**
215
+ * Consume a one-shot decision token for the effect that is about to run.
216
+ * Throws PolicyError (E_POLICY_TOKEN_*) when the token is invalid, expired,
217
+ * already used, tampered with, or when the effect does not match the digest.
218
+ *
219
+ * @param {object} token token returned by authorize()
220
+ * @param {object} effect same effect metadata that was authorized
221
+ * @param {{now?: Date|number|string}} [options]
222
+ * @returns {{decisionId: string, effectDigest: string, surface: string, action: string}}
223
+ */
224
+ export function consumeDecision(token, effect, options = {}) {
225
+ const at = nowMs(options.now)
226
+ const stored = assertToken(token)
227
+ if (at > stored.expiresAt) throw policyError('POLICY_TOKEN_EXPIRED', 'the decision token expired before the effect was executed')
228
+ const digest = effectDigestOf(effect)
229
+ if (digest !== stored.effectDigest) {
230
+ throw policyError('POLICY_TOKEN_EFFECT_MISMATCH', 'the effect does not match the effect digest the decision was issued for')
231
+ }
232
+ stored.used = true
233
+ return {
234
+ decisionId: stored.decisionId,
235
+ effectDigest: stored.effectDigest,
236
+ surface: stored.surface,
237
+ action: stored.action,
238
+ auditRequired: stored.requiresAudit === true,
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Consume the token, execute fn, and write the result audit row.
244
+ *
245
+ * The intent row was written by authorize(); this writes exactly one result
246
+ * row with ok=<boolean> (and the error code when fn throws) and rethrows the
247
+ * original error. A result-audit failure after the effect throws
248
+ * E_POLICY_AUDIT_UNAVAILABLE with effectCompleted:true: callers must surface
249
+ * that loudly (the effect already happened and is not audited).
250
+ *
251
+ * @param {object} token from authorize()
252
+ * @param {object} effect effect metadata
253
+ * @param {Function} fn synchronous effect executor
254
+ * @param {{now?: Date|number|string, audit?: Function, actor?: string}} [options]
255
+ */
256
+ export function runWithDecision(token, effect, fn, options = {}) {
257
+ if (typeof fn !== 'function') throw new TypeError('runWithDecision(token, effect, fn) requires a function')
258
+ if (!isPlainObject(options)) throw new TypeError('runWithDecision options must be an object')
259
+ const at = nowMs(options.now)
260
+ const consumed = consumeDecision(token, effect, { now: at })
261
+ const audit = options.audit
262
+ let result
263
+ try {
264
+ result = fn()
265
+ } catch (error) {
266
+ writeAudit(
267
+ audit,
268
+ auditEvent({
269
+ at: isoAt(at),
270
+ actor: options.actor,
271
+ surface: consumed.surface,
272
+ action: consumed.action,
273
+ policyAction: consumed.action,
274
+ phase: 'result',
275
+ decision: 'allow',
276
+ decisionId: consumed.decisionId,
277
+ effectDigest: consumed.effectDigest,
278
+ ok: false,
279
+ code: typeof error?.code === 'string' ? error.code : 'E_POLICY_EFFECT_FAILED',
280
+ }),
281
+ )
282
+ throw error
283
+ }
284
+ const wrote = writeAudit(
285
+ audit,
286
+ auditEvent({
287
+ at: isoAt(at),
288
+ actor: options.actor,
289
+ surface: consumed.surface,
290
+ action: consumed.action,
291
+ policyAction: consumed.action,
292
+ phase: 'result',
293
+ decision: 'allow',
294
+ decisionId: consumed.decisionId,
295
+ effectDigest: consumed.effectDigest,
296
+ ok: true,
297
+ }),
298
+ )
299
+ if (consumed.auditRequired && !wrote) {
300
+ throw policyError('POLICY_AUDIT_UNAVAILABLE', 'the effect completed but its result audit could not be written', { effectCompleted: true, decisionId: consumed.decisionId })
301
+ }
302
+ return result
303
+ }
304
+
305
+ /** Drop every issued token (tests, long-lived processes after a failure). */
306
+ export function clearDecisionTokens() {
307
+ tokens.clear()
308
+ }
309
+
310
+ /** Number of unexpired/unused tokens currently tracked (diagnostics). */
311
+ export function decisionTokenCount() {
312
+ return tokens.size
313
+ }
314
+
315
+ export { PolicyError, effectDigestOf, canonicalJson, EFFECT_DIGEST_FIELDS }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Egress registry (0.4 subset) + checkEgress(kind, meta).
3
+ *
4
+ * Why a registry: every place where data can leave the process (model, network,
5
+ * files, paths exported to a counterparty) must be discoverable from one list,
6
+ * so a new data surface cannot silently grow its own private gate. Each row
7
+ * records surface/action/dataClass/sink/entry/default/gate/tosRef plus the
8
+ * documentation clause that promises it.
9
+ *
10
+ * 0.4 registers the paths that exist at integration time (chat/capture/research/
11
+ * bridge model calls, IMAP sync, notify webhook, export packs) and the new
12
+ * mail.extract / kb.ask model paths landing in 0.4 (default off until consent
13
+ * exists). A static wiring gate (scripts/, lead-owned) can scan the model/net
14
+ * call sites and require each one to appear here; this module only owns the
15
+ * data + runtime check.
16
+ *
17
+ * lib/egress.js (matter secrecy guard) is intentionally untouched: it keeps its
18
+ * legacy exports/behaviour; this is an additive registry next to it.
19
+ */
20
+ import { policyError } from './errors.js'
21
+ import { evaluate } from './rules.js'
22
+ import { getSurface, normalizeSurface } from './surfaces.js'
23
+
24
+ /** Egress sink kinds: where data is going. */
25
+ export const EGRESS_SINKS = Object.freeze(['model', 'net', 'send', 'fs', 'export', 'spawn', 'local'])
26
+
27
+ const SINK_ALIASES = Object.freeze({
28
+ model: 'model',
29
+ 'model-egress': 'model',
30
+ chat: 'model',
31
+ llm: 'model',
32
+ net: 'net',
33
+ 'net-egress': 'net',
34
+ network: 'net',
35
+ webhook: 'net',
36
+ send: 'send',
37
+ mail: 'send',
38
+ fs: 'fs',
39
+ file: 'fs',
40
+ disk: 'fs',
41
+ export: 'export',
42
+ pack: 'export',
43
+ spawn: 'spawn',
44
+ exec: 'spawn',
45
+ local: 'local',
46
+ })
47
+
48
+ const RUNTIME_FACT_KEYS = Object.freeze([
49
+ 'facts', 'tos', 'consent', 'record', 'safety', 'trust', 'audit', 'path', 'clearance',
50
+ 'interactive', 'confirmed', 'dataClass', 'provider', 'baseUrl', 'actor', 'now',
51
+ ])
52
+
53
+ /**
54
+ * One row per registered egress path.
55
+ *
56
+ * default 'on' usable after the normal gates (TOS/key/config),
57
+ * 'off' requires an explicit local enablement (e.g. consent entry).
58
+ * gate matches the surface registry gate for the same surface.
59
+ */
60
+ export const EGRESS_REGISTRY = Object.freeze([
61
+ Object.freeze({ id: 'chat.model', surface: 'chat', action: 'model-egress', dataClass: 'conversation', sink: 'model', entry: 'lib/model.js#chatCompletion', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
62
+ Object.freeze({ id: 'capture.model', surface: 'capture', action: 'model-egress', dataClass: 'conversation', sink: 'model', entry: 'lib/capture.js#captureCandidates', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
63
+ Object.freeze({ id: 'research.model', surface: 'research', action: 'model-egress', dataClass: 'conversation', sink: 'model', entry: 'lib/research.js#research', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
64
+ Object.freeze({ id: 'agent.model', surface: 'agent', action: 'model-egress', dataClass: 'conversation', sink: 'model', entry: 'lib/agent.js#runAgent', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
65
+ Object.freeze({ id: 'bridge.model', surface: 'bridge', action: 'net-egress', dataClass: 'conversation', sink: 'net', entry: 'packages/bridge-hermes', default: 'off', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
66
+ Object.freeze({ id: 'notify.webhook', surface: 'notify.webhook', action: 'net-egress', dataClass: 'reminder', sink: 'net', entry: 'lib/notify.js#sendWebhookNotification', default: 'off', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
67
+ Object.freeze({ id: 'mail.sync', surface: 'mail.sync', action: 'net-egress', dataClass: 'mail', sink: 'net', entry: 'lib/mail.js#mailSync', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
68
+ Object.freeze({ id: 'mail.extract.model', surface: 'mail.extract', action: 'model-egress', dataClass: 'mail', sink: 'model', entry: 'lib/mail-extract.js#extractCandidatesWithModel', default: 'off', gate: 'enforced-policy', tosRef: 'docs/TOS.md#9.3' }),
69
+ Object.freeze({ id: 'kb.ask.model', surface: 'kb.ask', action: 'model-egress', dataClass: 'kb', sink: 'model', entry: 'lib/kb.js (model ask planned 0.4.x; local kbSearch ships in 0.4)', default: 'off', gate: 'enforced-policy', tosRef: 'docs/TOS.md#9.3' }),
70
+ Object.freeze({ id: 'export.evidence-pack', surface: 'export', action: 'export', dataClass: 'ledger', sink: 'fs', entry: 'lib/evidence.js#buildEvidencePack', default: 'on', gate: 'enforced-policy', tosRef: 'docs/TOS.md#9.3' }),
71
+ Object.freeze({ id: 'export.receipt-pack', surface: 'export', action: 'export', dataClass: 'ledger', sink: 'fs', entry: 'lib/evidence.js#buildReceiptPack', default: 'on', gate: 'enforced-policy', tosRef: 'docs/TOS.md#9.3' }),
72
+ Object.freeze({ id: 'export.pet-brief', surface: 'pet-brief', action: 'export', dataClass: 'ledger', sink: 'fs', entry: 'lib/pet-brief.js#buildPetBrief', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#9.3' }),
73
+ Object.freeze({ id: 'kb.ingest.local', surface: 'kb.ingest', action: 'write-ledger', dataClass: 'kb', sink: 'fs', entry: 'lib/kb.js#kbAdd', default: 'on', gate: 'self-attested', tosRef: 'docs/TOS.md#9.3' }),
74
+ Object.freeze({ id: 'agent.exec', surface: 'agent', action: 'exec', dataClass: 'tool', sink: 'spawn', entry: 'lib/agent.js#executeTool', default: 'on', gate: 'legacy-gate', tosRef: 'docs/TOS.md#5' }),
75
+ ])
76
+
77
+ const ENTRY_BY_ID = new Map(EGRESS_REGISTRY.map((entry) => [entry.id, entry]))
78
+
79
+ /** Canonical egress sink kind or null. */
80
+ export function normalizeEgressKind(value) {
81
+ if (typeof value !== 'string') return null
82
+ const key = value.trim().toLowerCase()
83
+ return SINK_ALIASES[key] ?? null
84
+ }
85
+
86
+ /** Deterministic JSON-ready registry copy (for docs/contract tests). */
87
+ export function listEgress() {
88
+ return EGRESS_REGISTRY.map((entry) => ({
89
+ id: entry.id,
90
+ surface: entry.surface,
91
+ action: entry.action,
92
+ dataClass: entry.dataClass,
93
+ sink: entry.sink,
94
+ entry: entry.entry,
95
+ default: entry.default,
96
+ gate: entry.gate,
97
+ tosRef: entry.tosRef,
98
+ }))
99
+ }
100
+
101
+ /** Registry row by id. */
102
+ export function getEgressEntry(id) {
103
+ return typeof id === 'string' ? ENTRY_BY_ID.get(id) ?? null : null
104
+ }
105
+
106
+ function matchEntries(kind, meta) {
107
+ const sink = normalizeEgressKind(kind)
108
+ if (!sink) return { sink: null, entries: [] }
109
+ if (typeof meta?.id === 'string' && meta.id) {
110
+ const entry = ENTRY_BY_ID.get(meta.id)
111
+ return { sink, entries: entry && entry.sink === sink ? [entry] : [] }
112
+ }
113
+ let entries = EGRESS_REGISTRY.filter((entry) => entry.sink === sink)
114
+ const surface = normalizeSurface(meta?.surface)
115
+ if (surface) entries = entries.filter((entry) => entry.surface === surface)
116
+ const action = typeof meta?.action === 'string' ? meta.action.trim() : ''
117
+ if (action) entries = entries.filter((entry) => entry.action === action)
118
+ const dataClass = typeof meta?.dataClass === 'string' ? meta.dataClass.trim() : ''
119
+ if (dataClass) entries = entries.filter((entry) => entry.dataClass === dataClass)
120
+ return { sink, entries }
121
+ }
122
+
123
+ /**
124
+ * Static registry lookup: the registered egress row for a sink + selector.
125
+ * Returns null for unknown/ambiguous paths (never guesses between rows).
126
+ *
127
+ * @param {string} kind sink ('model'|'net'|'send'|'fs'|'export'|'spawn'|'local')
128
+ * @param {{id?: string, surface?: string, action?: string, dataClass?: string}} [meta]
129
+ */
130
+ export function findEgressEntry(kind, meta = {}) {
131
+ const matched = matchEntries(kind, meta)
132
+ if (!matched.sink || matched.entries.length !== 1) return null
133
+ return matched.entries[0]
134
+ }
135
+
136
+ function registryOnlyResult(sink, entry) {
137
+ const surfaceRow = getSurface(entry.surface)
138
+ return {
139
+ v: 1,
140
+ kind: sink,
141
+ id: entry.id,
142
+ registered: true,
143
+ checked: false,
144
+ entry: listEgress().find((row) => row.id === entry.id),
145
+ gate: surfaceRow ? surfaceRow.gate : entry.gate,
146
+ default: entry.default,
147
+ decision: 'not_checked',
148
+ code: null,
149
+ policyCode: null,
150
+ ruleIds: [],
151
+ obligations: [],
152
+ reason: 'registry-only check: runtime facts (tos/audit/consent/record/safety) were not supplied; call evaluate() or pass them as meta to get a decision',
153
+ }
154
+ }
155
+
156
+ function hasRuntimeFacts(meta) {
157
+ if (!meta || typeof meta !== 'object') return false
158
+ return RUNTIME_FACT_KEYS.some((key) => Object.prototype.hasOwnProperty.call(meta, key))
159
+ }
160
+
161
+ function factsFromMeta(entry, meta) {
162
+ if (meta && typeof meta.facts === 'object' && meta.facts !== null) {
163
+ return {
164
+ ...meta.facts,
165
+ surface: meta.facts.surface ?? entry.surface,
166
+ action: meta.facts.action ?? entry.action,
167
+ dataClass: meta.facts.dataClass ?? entry.dataClass,
168
+ }
169
+ }
170
+ const facts = {}
171
+ for (const key of RUNTIME_FACT_KEYS) {
172
+ if (key === 'facts') continue
173
+ if (meta[key] !== undefined) facts[key] = meta[key]
174
+ }
175
+ facts.surface = typeof meta.surface === 'string' && meta.surface ? meta.surface : entry.surface
176
+ facts.action = typeof meta.action === 'string' && meta.action ? meta.action : entry.action
177
+ facts.dataClass = typeof meta.dataClass === 'string' && meta.dataClass ? meta.dataClass : entry.dataClass
178
+ if (meta.provider !== undefined) facts.provider = meta.provider
179
+ return facts
180
+ }
181
+
182
+ /**
183
+ * Check one egress path.
184
+ *
185
+ * 1. The sink must be known and the path registered (otherwise deny with
186
+ * E_POLICY_EGRESS_UNREGISTERED/E_POLICY_UNKNOWN_SURFACE).
187
+ * 2. When runtime facts are supplied (directly or as meta.facts), the call
188
+ * delegates to evaluate() and returns its decision with the registry row.
189
+ * 3. Without runtime facts it returns decision 'not_checked' (registry-only
190
+ * probe for docs gates/tests) instead of pretending to have checked.
191
+ *
192
+ * @param {string} kind egress sink
193
+ * @param {object} [meta] selector {id?, surface?, action?, dataClass?} + runtime facts
194
+ * @returns {object} JSON-ready {kind, registered, entry, decision, code,
195
+ * policyCode, ruleIds, obligations, reason, checked}
196
+ */
197
+ export function checkEgress(kind, meta = {}) {
198
+ if (meta !== undefined && meta !== null && (typeof meta !== 'object' || Array.isArray(meta))) {
199
+ throw new TypeError('checkEgress(kind, meta) requires a meta object')
200
+ }
201
+ const selector = meta || {}
202
+ const matched = matchEntries(kind, selector)
203
+ if (!matched.sink) {
204
+ const error = policyError('POLICY_EGRESS_UNREGISTERED', 'unknown egress sink kind')
205
+ return {
206
+ v: 1,
207
+ kind: null,
208
+ id: null,
209
+ registered: false,
210
+ checked: false,
211
+ entry: null,
212
+ decision: 'deny',
213
+ code: error.code,
214
+ policyCode: error.policyCode,
215
+ ruleIds: [],
216
+ obligations: [],
217
+ reason: 'unknown egress sink kind; register it before it can be used',
218
+ }
219
+ }
220
+ if (matched.entries.length === 0) {
221
+ const error = policyError('POLICY_EGRESS_UNREGISTERED', 'egress path is not registered')
222
+ return {
223
+ v: 1,
224
+ kind: matched.sink,
225
+ id: null,
226
+ registered: false,
227
+ checked: false,
228
+ entry: null,
229
+ decision: 'deny',
230
+ code: error.code,
231
+ policyCode: error.policyCode,
232
+ ruleIds: [],
233
+ obligations: [],
234
+ reason: 'egress path is not registered in the egress registry; new paths fail closed',
235
+ }
236
+ }
237
+ if (matched.entries.length > 1) {
238
+ return {
239
+ v: 1,
240
+ kind: matched.sink,
241
+ id: null,
242
+ registered: false,
243
+ checked: false,
244
+ entry: null,
245
+ candidates: matched.entries.map((entry) => entry.id).sort(),
246
+ decision: 'deny',
247
+ code: 'E_POLICY_EGRESS_UNREGISTERED',
248
+ policyCode: 'POLICY_EGRESS_UNREGISTERED',
249
+ ruleIds: [],
250
+ obligations: [],
251
+ reason: 'ambiguous egress path: pass meta.id (one of the candidates) to disambiguate',
252
+ }
253
+ }
254
+ const entry = matched.entries[0]
255
+ if (!hasRuntimeFacts(selector)) return registryOnlyResult(matched.sink, entry)
256
+ const facts = factsFromMeta(entry, selector)
257
+ const decision = evaluate(facts)
258
+ return {
259
+ ...decision,
260
+ kind: matched.sink,
261
+ id: entry.id,
262
+ registered: true,
263
+ checked: true,
264
+ entry: listEgress().find((row) => row.id === entry.id),
265
+ gate: getSurface(entry.surface) ? getSurface(entry.surface).gate : entry.gate,
266
+ default: entry.default,
267
+ }
268
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Policy error codes (0.4 subset): one place that maps an internal POLICY_*
3
+ * reason to the public E_* code carried by error envelopes and CLI stderr.
4
+ *
5
+ * 0.4 does not activate exit codes 4/5/6 (contracts/cli/errors-v1.schema.json is
6
+ * a closed schema); every code below keeps exit 1 except E_TOS_REQUIRED, which
7
+ * keeps its historical exit 3.
8
+ *
9
+ * Registration note for lead/integration: the new E_POLICY_* literals must be
10
+ * added to lib/error-codes.js (category 'policy', since '0.4.0') and regenerated
11
+ * with `node scripts/check-contracts.mjs --update`; this module only defines the
12
+ * runtime mapping so lib/ tests do not depend on bin/ wiring.
13
+ */
14
+
15
+ /** Public code + operational metadata for every internal policy reason. */
16
+ export const POLICY_CODES = Object.freeze({
17
+ POLICY_UNKNOWN_SURFACE: Object.freeze({ code: 'E_POLICY_UNKNOWN_SURFACE', exit: 1, category: 'policy', description: 'surface/action not registered; new paths fail closed' }),
18
+ POLICY_SURFACE_NOT_ENABLED: Object.freeze({ code: 'E_POLICY_SURFACE_NOT_ENABLED', exit: 1, category: 'policy', description: 'registered but not wired/enabled yet (matrix gate not-wired)' }),
19
+ POLICY_TOS_REQUIRED: Object.freeze({ code: 'E_TOS_REQUIRED', exit: 3, category: 'tos', description: 'current terms of service must be accepted' }),
20
+ POLICY_SECRECY_BLOCKED: Object.freeze({ code: 'E_SECRECY_BLOCKED', exit: 1, category: 'policy', description: 'record belongs to a protected matter; egress/export blocked for that item' }),
21
+ POLICY_CONSENT_REQUIRED: Object.freeze({ code: 'E_POLICY_CONSENT_REQUIRED', exit: 1, category: 'policy', description: 'model egress of mail/KB content requires an explicit consent record for surface+dataClass+provider' }),
22
+ POLICY_CONFIRMATION_UNAVAILABLE: Object.freeze({ code: 'E_POLICY_CONFIRMATION_UNAVAILABLE', exit: 1, category: 'policy', description: 'untrusted content would drive a side effect and no interactive confirmation channel is available' }),
23
+ POLICY_AUDIT_UNAVAILABLE: Object.freeze({ code: 'E_POLICY_AUDIT_UNAVAILABLE', exit: 1, category: 'policy', description: 'intent/result audit could not be written; the side effect is refused (fail closed)' }),
24
+ POLICY_PROTECTED_PATH: Object.freeze({ code: 'E_POLICY_PROTECTED_PATH', exit: 1, category: 'policy', description: 'target path is a protected or persistence location' }),
25
+ POLICY_WORKSPACE_ESCAPE: Object.freeze({ code: 'E_POLICY_WORKSPACE_ESCAPE', exit: 1, category: 'policy', description: 'target path escapes the workspace boundary' }),
26
+ POLICY_CONTENT_SAFETY_BLOCKED: Object.freeze({ code: 'E_CONTENT_SAFETY_BLOCKED', exit: 1, category: 'content', description: 'content safety classifier blocked the content' }),
27
+ POLICY_SAFETY_REQUIRED: Object.freeze({ code: 'E_POLICY_SAFETY_REQUIRED', exit: 1, category: 'policy', description: 'a content-safety verdict is required before this action but was not supplied' }),
28
+ POLICY_INVALID_FACTS: Object.freeze({ code: 'E_POLICY_INVALID_FACTS', exit: 1, category: 'policy', description: 'policy facts are malformed or incomplete; fail closed instead of guessing' }),
29
+ POLICY_EGRESS_UNREGISTERED: Object.freeze({ code: 'E_POLICY_EGRESS_UNREGISTERED', exit: 1, category: 'policy', description: 'egress sink/path is not registered in the egress registry' }),
30
+ POLICY_TOKEN_INVALID: Object.freeze({ code: 'E_POLICY_TOKEN_INVALID', exit: 1, category: 'policy', description: 'decision token is malformed or was tampered with' }),
31
+ POLICY_TOKEN_UNKNOWN: Object.freeze({ code: 'E_POLICY_TOKEN_UNKNOWN', exit: 1, category: 'policy', description: 'decision token was not issued by this process' }),
32
+ POLICY_TOKEN_EXPIRED: Object.freeze({ code: 'E_POLICY_TOKEN_EXPIRED', exit: 1, category: 'policy', description: 'decision token expired before the effect was executed' }),
33
+ POLICY_TOKEN_REPLAY: Object.freeze({ code: 'E_POLICY_TOKEN_REPLAY', exit: 1, category: 'policy', description: 'one-shot decision token was already consumed' }),
34
+ POLICY_TOKEN_EFFECT_MISMATCH: Object.freeze({ code: 'E_POLICY_TOKEN_EFFECT_MISMATCH', exit: 1, category: 'policy', description: 'effect does not match the effect digest the decision was issued for' }),
35
+ })
36
+
37
+ /** Internal reason -> public code lookup (unknown reasons fail closed). */
38
+ export function policyCodeFor(reason) {
39
+ const entry = POLICY_CODES[reason]
40
+ return entry ? entry.code : 'E_POLICY_INVALID_FACTS'
41
+ }
42
+
43
+ export function policyCodeExit(reason) {
44
+ const entry = POLICY_CODES[reason]
45
+ return entry ? entry.exit : 1
46
+ }
47
+
48
+ /** JSON-ready code registry (docs/contracts/check scripts and tests). */
49
+ export function policyCodeRegistry() {
50
+ return Object.keys(POLICY_CODES)
51
+ .sort()
52
+ .map((reason) => ({ reason, ...POLICY_CODES[reason] }))
53
+ }
54
+
55
+ /** A policy refusal with a stable public code; details are JSON-ready. */
56
+ export class PolicyError extends Error {
57
+ constructor(reason, message, details) {
58
+ const entry = POLICY_CODES[reason]
59
+ const code = entry ? entry.code : 'E_POLICY_INVALID_FACTS'
60
+ super(code + ': ' + (message || (entry ? entry.description : 'policy refused')))
61
+ this.name = 'PolicyError'
62
+ this.code = code
63
+ this.policyCode = reason
64
+ if (details && typeof details === 'object' && !Array.isArray(details)) this.details = { ...details }
65
+ }
66
+ }
67
+
68
+ /** Build a PolicyError for an internal policy reason. */
69
+ export function policyError(reason, message, details) {
70
+ return new PolicyError(reason, message, details)
71
+ }