@principles/host-runtime 5.1.0 → 5.3.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.
- package/dist/advisory-delivery.d.ts +34 -0
- package/dist/advisory-delivery.js +69 -0
- package/dist/behavior-history.js +1 -1
- package/dist/cli-recovery-probe.d.ts +23 -2
- package/dist/cli-recovery-probe.js +98 -9
- package/dist/codex-ingestion-consent.d.ts +5 -6
- package/dist/codex-ingestion-consent.js +5 -6
- package/dist/codex-rule-context-provider.js +30 -7
- package/dist/conversation-ingestion/consent.d.ts +14 -31
- package/dist/conversation-ingestion/consent.js +14 -223
- package/dist/fact-assembler.d.ts +91 -0
- package/dist/fact-assembler.js +318 -0
- package/dist/forward-observation.d.ts +6 -0
- package/dist/forward-observation.js +2 -1
- package/dist/host-liveness-contract.js +12 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +13 -32
- package/dist/internalization-consumer-cycle.js +1 -1
- package/dist/mode-state-facts.d.ts +41 -0
- package/dist/mode-state-facts.js +224 -0
- package/dist/pain-inbox.d.ts +28 -0
- package/dist/pain-inbox.js +194 -46
- package/dist/product-telemetry/consent-store.d.ts +9 -47
- package/dist/product-telemetry/consent-store.js +18 -131
- package/dist/production-pain-evidence.d.ts +9 -0
- package/dist/production-pain-evidence.js +22 -2
- package/dist/production-policy-gate.d.ts +104 -0
- package/dist/production-policy-gate.js +379 -0
- package/dist/production-rulehost-gate.d.ts +6 -0
- package/dist/production-rulehost-gate.js +160 -31
- package/dist/prompt-activation-event.d.ts +29 -0
- package/dist/prompt-activation-event.js +80 -0
- package/dist/prompt-injection-budget-observation.d.ts +0 -11
- package/dist/prompt-injection-budget-observation.js +0 -11
- package/dist/rule-policy-active.d.ts +80 -0
- package/dist/rule-policy-active.js +197 -0
- package/dist/rule-policy-host-defaults.d.ts +19 -0
- package/dist/rule-policy-host-defaults.js +12 -0
- package/dist/rule-policy-paths-fs.d.ts +20 -0
- package/dist/rule-policy-paths-fs.js +58 -0
- package/dist/rule-policy-replay-evidence.d.ts +52 -0
- package/dist/rule-policy-replay-evidence.js +259 -0
- package/dist/session-write-targets.d.ts +86 -0
- package/dist/session-write-targets.js +216 -0
- package/dist/signal-classifier.d.ts +1 -0
- package/dist/signal-classifier.js +1 -1
- package/dist/signal-rate-limiter.d.ts +34 -0
- package/dist/signal-rate-limiter.js +83 -0
- package/dist/trajectory-retention.d.ts +8 -0
- package/dist/trajectory-retention.js +29 -0
- package/dist/trusted-pd-binary.d.ts +10 -0
- package/dist/trusted-pd-binary.js +38 -0
- package/dist/workbuddy-rule-context-provider.js +31 -10
- package/dist/workspace-behavior-evidence.d.ts +55 -0
- package/dist/workspace-behavior-evidence.js +93 -0
- package/package.json +24 -4
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mode-state fact loader (SPEC-PD-RULE-POLICY-001 Requirement 8; design.md §8).
|
|
3
|
+
*
|
|
4
|
+
* Reads one session's Mode_Store records and live Decision_Ledger reminders from the
|
|
5
|
+
* governance workspace connection the gate already holds, and returns the
|
|
6
|
+
* `ModeStateFact` the policy evaluator consumes.
|
|
7
|
+
*
|
|
8
|
+
* Trust boundary: every input of `loadModeStateFact` comes from the host event or from
|
|
9
|
+
* the host's own configuration. There is deliberately NO parameter that carries tool
|
|
10
|
+
* arguments, because the values below are rendered into commands the agent is told to
|
|
11
|
+
* run; a path or id taken from a tool call would let the agent steer that command.
|
|
12
|
+
*
|
|
13
|
+
* Failure is never silent (rc-9): any read error becomes `status: 'unavailable'` with a
|
|
14
|
+
* bounded reason, which the evaluator turns into `unknown` (never into a reminder or block).
|
|
15
|
+
*/
|
|
16
|
+
import * as fs from 'node:fs';
|
|
17
|
+
import * as path from 'node:path';
|
|
18
|
+
import { SqliteDecisionLedgerStore, SqliteModeDeclarationStore, checkHostSessionId, } from '@principles/core/runtime/internalization/rule-policy-modes';
|
|
19
|
+
import { toPolicyPathKey } from '@principles/core/runtime/internalization/rule-policy-paths';
|
|
20
|
+
import { realPathForPolicyTarget } from './rule-policy-paths-fs.js';
|
|
21
|
+
const REASON_MAX = 300;
|
|
22
|
+
const LABEL_SLUG_MAX = 40;
|
|
23
|
+
const SESSION_PREFIX_LENGTH = 8;
|
|
24
|
+
const MODES_DIR = '.principles/modes';
|
|
25
|
+
const RULE_ID_PLACEHOLDER = '{ruleId}';
|
|
26
|
+
const REASON_PLACEHOLDER = {
|
|
27
|
+
'zh-CN': '<写明为什么这次不适用>',
|
|
28
|
+
en: '<say why this does not apply this time>',
|
|
29
|
+
};
|
|
30
|
+
function emptyFact() {
|
|
31
|
+
return {
|
|
32
|
+
version: 1,
|
|
33
|
+
acts: {},
|
|
34
|
+
scopePaths: null,
|
|
35
|
+
scopeRevision: null,
|
|
36
|
+
latestSituationClass: null,
|
|
37
|
+
waiversByRule: {},
|
|
38
|
+
remindersByRule: {},
|
|
39
|
+
declareHint: null,
|
|
40
|
+
waiveHint: null,
|
|
41
|
+
suggestedFile: null,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function unavailable(reason) {
|
|
45
|
+
const text = reason.replace(/\s+/g, ' ').trim().slice(0, REASON_MAX);
|
|
46
|
+
return { ...emptyFact(), status: 'unavailable', unavailableReason: text.length > 0 ? text : 'unknown' };
|
|
47
|
+
}
|
|
48
|
+
function isRecord(value) {
|
|
49
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
50
|
+
}
|
|
51
|
+
// ── hint values ────────────────────────────────────────────────────────────
|
|
52
|
+
function hasControlCharacter(value) {
|
|
53
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
54
|
+
const code = value.charCodeAt(i);
|
|
55
|
+
if (code < 0x20 || code === 0x7f)
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Values inside double quotes must not be able to end the quote, expand, or span lines:
|
|
62
|
+
* the agent is told to run these commands, and the Recovery_Marker recogniser refuses any
|
|
63
|
+
* command with expansion anyway.
|
|
64
|
+
*/
|
|
65
|
+
function isSafeQuotedValue(value) {
|
|
66
|
+
return value.length > 0 && !/["`$]/.test(value) && !hasControlCharacter(value);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A bare word or path without spaces or shell syntax, or one pair of double quotes around
|
|
70
|
+
* a safe value (a path with spaces). Backslashes are allowed so `C:\Users\x\pd.cmd` works.
|
|
71
|
+
*/
|
|
72
|
+
function isSafePdBin(value) {
|
|
73
|
+
if (value.length >= 2 && value.startsWith('"') && value.endsWith('"'))
|
|
74
|
+
return isSafeQuotedValue(value.slice(1, -1));
|
|
75
|
+
return value.length > 0 && !/[\s"'`$;&|<>(){}*?[\]#~!]/.test(value) && !hasControlCharacter(value);
|
|
76
|
+
}
|
|
77
|
+
function slug(text) {
|
|
78
|
+
const cleaned = (text ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, LABEL_SLUG_MAX).replace(/-+$/g, '');
|
|
79
|
+
return cleaned.length > 0 ? cleaned : 'mode';
|
|
80
|
+
}
|
|
81
|
+
function sessionPrefix(sessionId) {
|
|
82
|
+
const cleaned = sessionId.slice(0, SESSION_PREFIX_LENGTH).replace(/[^A-Za-z0-9_-]/g, '-');
|
|
83
|
+
return cleaned.length > 0 ? cleaned : 'session';
|
|
84
|
+
}
|
|
85
|
+
function buildHints(q, sessionId) {
|
|
86
|
+
const values = [q.governanceWorkspaceDir, q.projectRoot, sessionId];
|
|
87
|
+
if (q.pdBin === null || !isSafePdBin(q.pdBin) || !values.every(isSafeQuotedValue))
|
|
88
|
+
return null;
|
|
89
|
+
const suggestedFile = `${MODES_DIR}/${slug(q.labelHint)}-${sessionPrefix(sessionId)}.json`;
|
|
90
|
+
const common = `--workspace "${q.governanceWorkspaceDir}" --project "${q.projectRoot}" --session "${sessionId}"`;
|
|
91
|
+
const reason = REASON_PLACEHOLDER[q.locale ?? 'zh-CN'];
|
|
92
|
+
return {
|
|
93
|
+
declareHint: `${q.pdBin} mode declare ${common} --file "${suggestedFile}"`,
|
|
94
|
+
// `{ruleId}` stays literal: the message renderer substitutes the rule being blocked.
|
|
95
|
+
waiveHint: `${q.pdBin} mode waive ${common} --rule "${RULE_ID_PLACEHOLDER}" --reason "${reason}"`,
|
|
96
|
+
suggestedFile,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
// ── scope ──────────────────────────────────────────────────────────────────
|
|
100
|
+
/**
|
|
101
|
+
* Policy keys for the project-relative `inScope` entries of a declaration, or null when
|
|
102
|
+
* ANY entry cannot be converted (or none exist). A partly converted scope would silently
|
|
103
|
+
* shrink the allowed area and flag legitimate writes as drift, so the whole scope is
|
|
104
|
+
* treated as untrusted instead.
|
|
105
|
+
*/
|
|
106
|
+
export function toScopeKeys(inScope, projectRoot, platform) {
|
|
107
|
+
if (inScope.length === 0)
|
|
108
|
+
return null;
|
|
109
|
+
const root = projectRoot.replace(/[\\/]+$/, '');
|
|
110
|
+
let realRoot = null;
|
|
111
|
+
if (platform === process.platform && path.isAbsolute(projectRoot) && fs.existsSync(projectRoot)) {
|
|
112
|
+
const resolvedRoot = realPathForPolicyTarget(path.resolve(projectRoot));
|
|
113
|
+
if (!resolvedRoot.ok)
|
|
114
|
+
return null;
|
|
115
|
+
realRoot = resolvedRoot.path;
|
|
116
|
+
}
|
|
117
|
+
const keys = [];
|
|
118
|
+
for (const entry of inScope) {
|
|
119
|
+
const kept = entry.split(/[\\/]/).filter((segment) => segment !== '' && segment !== '.');
|
|
120
|
+
if (kept.length === 0 || kept.includes('..'))
|
|
121
|
+
return null;
|
|
122
|
+
const key = toPolicyPathKey(`${root}/${kept.join('/')}`, projectRoot, platform);
|
|
123
|
+
if (key === null || key === '')
|
|
124
|
+
return null;
|
|
125
|
+
if (realRoot !== null) {
|
|
126
|
+
const resolvedEntry = realPathForPolicyTarget(path.resolve(projectRoot, ...kept));
|
|
127
|
+
if (!resolvedEntry.ok)
|
|
128
|
+
return null;
|
|
129
|
+
const realKey = toPolicyPathKey(resolvedEntry.path, realRoot, platform);
|
|
130
|
+
if (realKey === null || realKey === '')
|
|
131
|
+
return null;
|
|
132
|
+
keys.push(realKey);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
keys.push(key);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return keys;
|
|
139
|
+
}
|
|
140
|
+
// ── load ───────────────────────────────────────────────────────────────────
|
|
141
|
+
function customAnswerIdsOf(declarationActs, actId) {
|
|
142
|
+
const output = Object.hasOwn(declarationActs, actId) ? declarationActs[actId] : undefined;
|
|
143
|
+
if (!isRecord(output) || !Object.hasOwn(output, 'customAnswers'))
|
|
144
|
+
return [];
|
|
145
|
+
const answers = output.customAnswers;
|
|
146
|
+
return isRecord(answers) ? Object.keys(answers) : [];
|
|
147
|
+
}
|
|
148
|
+
function groupAscending(entries) {
|
|
149
|
+
const grouped = new Map();
|
|
150
|
+
for (const [ruleId, at] of entries) {
|
|
151
|
+
const times = grouped.get(ruleId) ?? [];
|
|
152
|
+
times.push(at);
|
|
153
|
+
grouped.set(ruleId, times);
|
|
154
|
+
}
|
|
155
|
+
// ISO timestamps from the stores share one format, so lexicographic order is chronological.
|
|
156
|
+
return Object.fromEntries([...grouped].map(([ruleId, times]) => [ruleId, [...times].sort()]));
|
|
157
|
+
}
|
|
158
|
+
function describeError(error) {
|
|
159
|
+
const code = isRecord(error) && typeof error.code === 'string' ? `${error.code}: ` : '';
|
|
160
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
161
|
+
return `mode_state_read_failed: ${code}${message}`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Mode state of one session. Never throws: a failure to read is `unavailable` with a reason.
|
|
165
|
+
*/
|
|
166
|
+
export function loadModeStateFact(q) {
|
|
167
|
+
const session = checkHostSessionId(q.hostSessionId);
|
|
168
|
+
if (!session.ok)
|
|
169
|
+
return unavailable(`session_id_invalid: ${session.reason}`);
|
|
170
|
+
const hints = q.pdBin === null
|
|
171
|
+
? { declareHint: null, waiveHint: null, suggestedFile: null }
|
|
172
|
+
: buildHints(q, session.sessionId);
|
|
173
|
+
if (hints === null) {
|
|
174
|
+
return unavailable('hint_unsafe_value: a workspace, project, session id or pd binary contains a quote, expansion or control character, so no recovery command can be rendered safely');
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
if (q.hostKind === undefined)
|
|
178
|
+
return unavailable('host_kind_unavailable: the gate did not identify the host, so mode state cannot be attributed');
|
|
179
|
+
const platform = q.platform ?? process.platform;
|
|
180
|
+
const records = new SqliteModeDeclarationStore(q.governanceDb, { platform }).listForSession(q.hostKind, q.projectRoot, session.sessionId);
|
|
181
|
+
const allReminders = new SqliteDecisionLedgerStore(q.governanceDb).listRemindersForSession(q.hostKind, q.projectRoot, session.sessionId);
|
|
182
|
+
const acts = {};
|
|
183
|
+
let latestSituationClass = null;
|
|
184
|
+
let scopeSource = null;
|
|
185
|
+
const waivers = [];
|
|
186
|
+
for (const record of records) {
|
|
187
|
+
if (record.recordKind === 'waiver') {
|
|
188
|
+
waivers.push([record.ruleId, record.recordedAt]);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
latestSituationClass = record.situationClass;
|
|
192
|
+
for (const actId of record.actIds) {
|
|
193
|
+
const crossCheck = record.crossCheck?.[actId];
|
|
194
|
+
acts[actId] = {
|
|
195
|
+
recordedAt: record.recordedAt,
|
|
196
|
+
revision: record.revision,
|
|
197
|
+
customAnswerIds: customAnswerIdsOf(record.declaration.acts, actId),
|
|
198
|
+
...(crossCheck === undefined ? {} : { crossCheck: { kind: crossCheck.kind, score: crossCheck.score } }),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
if (record.scopePaths !== null)
|
|
202
|
+
scopeSource = { inScope: record.scopePaths, revision: record.revision };
|
|
203
|
+
}
|
|
204
|
+
const scopePaths = scopeSource === null ? null : toScopeKeys(scopeSource.inScope, q.projectRoot, platform);
|
|
205
|
+
const wanted = new Set(q.ruleIds);
|
|
206
|
+
const remindersByRule = groupAscending(Object.entries(allReminders).filter(([ruleId]) => wanted.has(ruleId)).flatMap(([ruleId, times]) => times.map((at) => [ruleId, at])));
|
|
207
|
+
const declared = latestSituationClass !== null;
|
|
208
|
+
return {
|
|
209
|
+
...emptyFact(),
|
|
210
|
+
status: declared ? 'declared' : 'absent',
|
|
211
|
+
acts: declared ? acts : {},
|
|
212
|
+
scopePaths: declared ? scopePaths : null,
|
|
213
|
+
scopeRevision: declared && scopePaths !== null && scopeSource !== null ? scopeSource.revision : null,
|
|
214
|
+
latestSituationClass,
|
|
215
|
+
waiversByRule: groupAscending(waivers),
|
|
216
|
+
remindersByRule,
|
|
217
|
+
...hints,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
return unavailable(describeError(error));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
export { resolveTrustedPdBinary } from './trusted-pd-binary.js';
|
package/dist/pain-inbox.d.ts
CHANGED
|
@@ -48,11 +48,13 @@ export interface PainInboxItem {
|
|
|
48
48
|
readonly reason: string | null;
|
|
49
49
|
readonly createdAt: string;
|
|
50
50
|
readonly expiresAt: string;
|
|
51
|
+
readonly snoozedUntil?: string | null;
|
|
51
52
|
}
|
|
52
53
|
export interface ListPainInboxResult {
|
|
53
54
|
readonly ok: true;
|
|
54
55
|
readonly items: readonly PainInboxItem[];
|
|
55
56
|
readonly total: number;
|
|
57
|
+
readonly snoozedCount: number;
|
|
56
58
|
readonly byHost: {
|
|
57
59
|
readonly openclaw: number;
|
|
58
60
|
readonly codex: number;
|
|
@@ -97,6 +99,26 @@ export type DismissInboxCandidateResult = {
|
|
|
97
99
|
readonly reason: string;
|
|
98
100
|
readonly nextAction: string;
|
|
99
101
|
};
|
|
102
|
+
interface SetSnoozeInput {
|
|
103
|
+
readonly workspaceDir: string;
|
|
104
|
+
readonly itemId: string;
|
|
105
|
+
readonly nowIso?: string;
|
|
106
|
+
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
107
|
+
}
|
|
108
|
+
type SetSnoozeResult = {
|
|
109
|
+
readonly ok: true;
|
|
110
|
+
readonly disposition: 'snoozed';
|
|
111
|
+
readonly itemId: string;
|
|
112
|
+
readonly snoozedUntil: string;
|
|
113
|
+
} | {
|
|
114
|
+
readonly ok: true;
|
|
115
|
+
readonly disposition: 'unsnoozed' | 'not_found' | 'already_resolved';
|
|
116
|
+
readonly itemId: string;
|
|
117
|
+
} | {
|
|
118
|
+
readonly ok: false;
|
|
119
|
+
readonly reason: 'invalid_snooze_time' | 'inbox_snooze_schema_incompatible' | 'inbox_snooze_write_failed';
|
|
120
|
+
readonly nextAction: string;
|
|
121
|
+
};
|
|
100
122
|
export interface ExpireStalePainInboxResult {
|
|
101
123
|
readonly ok: boolean;
|
|
102
124
|
readonly expiredGsa: number;
|
|
@@ -110,6 +132,10 @@ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
|
|
|
110
132
|
stateManager: Pick<RuntimeStateManager, 'updateTaskIfDiagnosticJsonUnchanged'>;
|
|
111
133
|
execute: () => Promise<PainSignalBridgeResult>;
|
|
112
134
|
}): Promise<PainSignalBridgeResult>;
|
|
135
|
+
export declare function snoozePainInboxCandidate(input: SetSnoozeInput & {
|
|
136
|
+
readonly snoozedUntilIso: string;
|
|
137
|
+
}): SetSnoozeResult;
|
|
138
|
+
export declare function unsnoozePainInboxCandidate(input: SetSnoozeInput): SetSnoozeResult;
|
|
113
139
|
/**
|
|
114
140
|
* List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
|
|
115
141
|
* Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
|
|
@@ -118,6 +144,7 @@ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
|
|
|
118
144
|
export declare function listPainInboxItems(input: {
|
|
119
145
|
readonly workspaceDir: string;
|
|
120
146
|
readonly hostFilter?: PainInboxHostKind;
|
|
147
|
+
readonly includeSnoozed?: boolean;
|
|
121
148
|
readonly now?: Date;
|
|
122
149
|
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
123
150
|
}): ListPainInboxResult;
|
|
@@ -143,3 +170,4 @@ export declare function expireStalePainInboxItems(input: {
|
|
|
143
170
|
readonly now?: Date;
|
|
144
171
|
readonly databaseFactory?: ObservationDatabaseFactory;
|
|
145
172
|
}): ExpireStalePainInboxResult;
|
|
173
|
+
export {};
|
package/dist/pain-inbox.js
CHANGED
|
@@ -34,11 +34,14 @@ import path from 'node:path';
|
|
|
34
34
|
import { isDeepStrictEqual } from 'node:util';
|
|
35
35
|
import Database from 'better-sqlite3';
|
|
36
36
|
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
37
|
+
import { convergeTrajectorySchemaVersion } from '@principles/core/runtime/trajectory-schema';
|
|
37
38
|
import { checkIngressTopLevelConsistency, createDiagnosticianTaskId, evaluatePainIngress, parsePainIngressV1Payload, } from '@principles/core/runtime';
|
|
38
39
|
import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
|
|
39
40
|
import { readSourceMaterialAuthorization } from './source-material-authorization.js';
|
|
40
41
|
import { ensureGovernanceDiagnosticianTask } from './governance-signal-admission.js';
|
|
41
42
|
export const PAIN_INBOX_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
43
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
44
|
+
const SNOOZE_REVIEW_WINDOW_MS = 24 * HOUR_MS;
|
|
42
45
|
export const PAIN_INBOX_APPROVING_TTL_MS = 10 * 60 * 1000;
|
|
43
46
|
function isRecord(value) {
|
|
44
47
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
@@ -390,15 +393,141 @@ function parseItemId(itemId) {
|
|
|
390
393
|
}
|
|
391
394
|
return null;
|
|
392
395
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
+
// signal_confirmations is part of an exact-DDL trajectory baseline: adding
|
|
397
|
+
// columns to it would stop old and current runtime writers opening the DB.
|
|
398
|
+
const SNOOZE_TABLE = 'pain_inbox_snoozes';
|
|
399
|
+
function readSnooze(db, itemId, createdAt) {
|
|
400
|
+
return tableExists(db, SNOOZE_TABLE)
|
|
401
|
+
? db.prepare('SELECT snoozed_until, review_until FROM pain_inbox_snoozes WHERE item_id = ? AND inbox_created_at = ?').get(itemId, createdAt)
|
|
402
|
+
: undefined;
|
|
396
403
|
}
|
|
397
|
-
function
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
404
|
+
function pruneExpiredSnoozes(db, nowIso) {
|
|
405
|
+
if (tableExists(db, SNOOZE_TABLE)) {
|
|
406
|
+
db.prepare('DELETE FROM pain_inbox_snoozes WHERE review_until <= ?').run(nowIso);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function activeSnoozeUntil(row, nowMs) {
|
|
410
|
+
return row.snoozed_until != null && Date.parse(row.snoozed_until) > nowMs ? row.snoozed_until : null;
|
|
411
|
+
}
|
|
412
|
+
function isExpired(createdAt, nowMs, reviewUntil) {
|
|
413
|
+
return Date.parse(createdAt) + PAIN_INBOX_TTL_MS <= nowMs
|
|
414
|
+
&& !(reviewUntil != null && Date.parse(reviewUntil) > nowMs);
|
|
415
|
+
}
|
|
416
|
+
function computeExpiresAt(createdAt, nowMs, reviewUntil) {
|
|
417
|
+
const createdMs = Date.parse(createdAt);
|
|
418
|
+
return new Date(Math.max((Number.isFinite(createdMs) ? createdMs : nowMs) + PAIN_INBOX_TTL_MS, reviewUntil == null ? 0 : (Date.parse(reviewUntil) || 0))).toISOString();
|
|
419
|
+
}
|
|
420
|
+
function isInboxHostAuthorized(workspaceDir, hostKind) {
|
|
421
|
+
const auth = readSourceMaterialAuthorization({ workspaceDir, hostKind });
|
|
422
|
+
return auth.status === 'authorized' || (hostKind === 'openclaw' && auth.reason === 'consent_missing');
|
|
423
|
+
}
|
|
424
|
+
function parseIsoMs(value) {
|
|
425
|
+
const parts = /^(\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d)(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value);
|
|
426
|
+
if (!parts)
|
|
427
|
+
return NaN;
|
|
428
|
+
const local = `${parts[1]}.${(parts[2] ?? '').padEnd(3, '0')}Z`;
|
|
429
|
+
const localMs = Date.parse(local);
|
|
430
|
+
if (!Number.isFinite(localMs) || new Date(localMs).toISOString() !== local)
|
|
431
|
+
return NaN;
|
|
432
|
+
return Date.parse(value);
|
|
433
|
+
}
|
|
434
|
+
function setInboxSnooze(input, nowMs, dueMs) {
|
|
435
|
+
const { workspaceDir, itemId, databaseFactory } = input;
|
|
436
|
+
const notFound = { ok: true, disposition: 'not_found', itemId };
|
|
437
|
+
const parsed = parseItemId(itemId);
|
|
438
|
+
if (!parsed)
|
|
439
|
+
return notFound;
|
|
440
|
+
let opened = null;
|
|
441
|
+
try {
|
|
442
|
+
opened = openTrajectoryDb(workspaceDir, false, databaseFactory);
|
|
443
|
+
if (!opened)
|
|
444
|
+
return notFound;
|
|
445
|
+
const { db } = opened;
|
|
446
|
+
// RESERVE the writer lock before reading the authoritative status.
|
|
447
|
+
// Approval, dismissal and expiry cannot interleave with this CAS.
|
|
448
|
+
return db.transaction(() => {
|
|
449
|
+
const isGsa = parsed.source === 'gsa';
|
|
450
|
+
const table = isGsa ? 'governance_signal_admissions' : 'signal_confirmations';
|
|
451
|
+
if (!tableExists(db, table))
|
|
452
|
+
return notFound;
|
|
453
|
+
const row = db.prepare(isGsa
|
|
454
|
+
? "SELECT host_kind AS host, created_at, decision = 'inbox_candidate' AS active FROM governance_signal_admissions WHERE logical_observation_key = ?"
|
|
455
|
+
: "SELECT 'openclaw' AS host, created_at, (status = 'pending' AND resolution = 'inbox_candidate') AS active FROM signal_confirmations WHERE id = ?").get(parsed.rawKey);
|
|
456
|
+
if (!row)
|
|
457
|
+
return notFound;
|
|
458
|
+
if (row.active !== 1)
|
|
459
|
+
return { ok: true, disposition: 'already_resolved', itemId };
|
|
460
|
+
if ((row.host !== 'openclaw' && row.host !== 'codex' && row.host !== 'workbuddy')
|
|
461
|
+
|| !isInboxHostAuthorized(workspaceDir, row.host))
|
|
462
|
+
return notFound;
|
|
463
|
+
const current = readSnooze(db, itemId, row.created_at);
|
|
464
|
+
if (isExpired(row.created_at, nowMs, current?.review_until)) {
|
|
465
|
+
return { ok: true, disposition: 'already_resolved', itemId };
|
|
466
|
+
}
|
|
467
|
+
// v3's explicit migration rejects undeclared tables. Validate the
|
|
468
|
+
// existing trajectory schema inside the writer lock before any DDL
|
|
469
|
+
// or metadata cleanup. List and the existing owner actions are unchanged.
|
|
470
|
+
try {
|
|
471
|
+
convergeTrajectorySchemaVersion(db);
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
if (!(error instanceof Error) || !error.message.startsWith('trajectory schema baseline incompatible:')) {
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
ok: false, reason: 'inbox_snooze_schema_incompatible',
|
|
479
|
+
nextAction: 'Upgrade or repair the workspace trajectory database before changing Pain Inbox reminders.',
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
pruneExpiredSnoozes(db, new Date(nowMs).toISOString());
|
|
483
|
+
if (dueMs === null) {
|
|
484
|
+
if (current?.snoozed_until) {
|
|
485
|
+
// An already surfaced item keeps its existing review deadline.
|
|
486
|
+
const reviewUntil = Date.parse(current.snoozed_until) > nowMs
|
|
487
|
+
? new Date(nowMs + SNOOZE_REVIEW_WINDOW_MS).toISOString()
|
|
488
|
+
: current.review_until;
|
|
489
|
+
db.prepare(`UPDATE pain_inbox_snoozes SET snoozed_until = NULL, review_until = ?
|
|
490
|
+
WHERE item_id = ? AND inbox_created_at = ?`).run(reviewUntil, itemId, row.created_at);
|
|
491
|
+
}
|
|
492
|
+
return { ok: true, disposition: 'unsnoozed', itemId };
|
|
493
|
+
}
|
|
494
|
+
const snoozedUntil = new Date(dueMs).toISOString();
|
|
495
|
+
db.exec(`CREATE TABLE IF NOT EXISTS pain_inbox_snoozes (
|
|
496
|
+
item_id TEXT PRIMARY KEY NOT NULL,
|
|
497
|
+
inbox_created_at TEXT NOT NULL,
|
|
498
|
+
snoozed_until TEXT,
|
|
499
|
+
review_until TEXT NOT NULL
|
|
500
|
+
)`);
|
|
501
|
+
db.prepare(`INSERT INTO pain_inbox_snoozes (item_id, inbox_created_at, snoozed_until, review_until)
|
|
502
|
+
VALUES (?, ?, ?, ?) ON CONFLICT(item_id) DO UPDATE SET
|
|
503
|
+
inbox_created_at = excluded.inbox_created_at,
|
|
504
|
+
snoozed_until = excluded.snoozed_until, review_until = excluded.review_until`)
|
|
505
|
+
.run(itemId, row.created_at, snoozedUntil, new Date(dueMs + SNOOZE_REVIEW_WINDOW_MS).toISOString());
|
|
506
|
+
return { ok: true, disposition: 'snoozed', itemId, snoozedUntil };
|
|
507
|
+
}).immediate();
|
|
508
|
+
}
|
|
509
|
+
catch {
|
|
510
|
+
return { ok: false, reason: 'inbox_snooze_write_failed', nextAction: 'Retry the Pain Inbox action; if it still fails, check workspace database access.' };
|
|
511
|
+
}
|
|
512
|
+
finally {
|
|
513
|
+
opened?.close();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
export function snoozePainInboxCandidate(input) {
|
|
517
|
+
const nowMs = input.nowIso === undefined ? Date.now() : parseIsoMs(input.nowIso);
|
|
518
|
+
const dueMs = parseIsoMs(input.snoozedUntilIso);
|
|
519
|
+
if (!Number.isFinite(nowMs) || !Number.isFinite(dueMs)
|
|
520
|
+
|| dueMs - nowMs < HOUR_MS || dueMs - nowMs > 30 * 24 * HOUR_MS) {
|
|
521
|
+
return { ok: false, reason: 'invalid_snooze_time', nextAction: 'Specify a valid ISO timestamp between 1 hour and 30 days from now.' };
|
|
522
|
+
}
|
|
523
|
+
return setInboxSnooze(input, nowMs, dueMs);
|
|
524
|
+
}
|
|
525
|
+
export function unsnoozePainInboxCandidate(input) {
|
|
526
|
+
const nowMs = input.nowIso === undefined ? Date.now() : parseIsoMs(input.nowIso);
|
|
527
|
+
if (!Number.isFinite(nowMs)) {
|
|
528
|
+
return { ok: false, reason: 'invalid_snooze_time', nextAction: 'Specify a valid ISO timestamp for now.' };
|
|
529
|
+
}
|
|
530
|
+
return setInboxSnooze(input, nowMs, null);
|
|
402
531
|
}
|
|
403
532
|
/**
|
|
404
533
|
* List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
|
|
@@ -409,25 +538,31 @@ export function listPainInboxItems(input) {
|
|
|
409
538
|
const nowMs = (input.now ?? new Date()).getTime();
|
|
410
539
|
const opened = openTrajectoryDb(input.workspaceDir, true, input.databaseFactory);
|
|
411
540
|
if (!opened) {
|
|
412
|
-
return { ok: true, items: [], total: 0, byHost: { openclaw: 0, codex: 0, workbuddy: 0 } };
|
|
541
|
+
return { ok: true, items: [], total: 0, snoozedCount: 0, byHost: { openclaw: 0, codex: 0, workbuddy: 0 } };
|
|
413
542
|
}
|
|
414
543
|
const { db, close } = opened;
|
|
415
544
|
try {
|
|
416
545
|
const items = [];
|
|
546
|
+
let snoozedCount = 0;
|
|
547
|
+
const hasSnoozes = tableExists(db, SNOOZE_TABLE);
|
|
548
|
+
const projectSnooze = hasSnoozes ? ', s.snoozed_until, s.review_until' : '';
|
|
549
|
+
const joinSnoozes = (idSql) => hasSnoozes
|
|
550
|
+
? `LEFT JOIN pain_inbox_snoozes s ON s.item_id = ${idSql} AND s.inbox_created_at = i.created_at`
|
|
551
|
+
: '';
|
|
552
|
+
const visible = (row) => {
|
|
553
|
+
if (isExpired(row.created_at, nowMs, row.review_until))
|
|
554
|
+
return false;
|
|
555
|
+
const snoozed = activeSnoozeUntil(row, nowMs) !== null;
|
|
556
|
+
if (snoozed)
|
|
557
|
+
snoozedCount++;
|
|
558
|
+
return input.includeSnoozed === true || !snoozed;
|
|
559
|
+
};
|
|
417
560
|
const authCache = new Map();
|
|
418
561
|
const isHostAuthorized = (hostKind) => {
|
|
419
562
|
const cached = authCache.get(hostKind);
|
|
420
563
|
if (cached !== undefined)
|
|
421
564
|
return cached;
|
|
422
|
-
|
|
423
|
-
// consent prerequisite unless explicitly revoked in the ledger.
|
|
424
|
-
const auth = readSourceMaterialAuthorization({
|
|
425
|
-
workspaceDir: input.workspaceDir,
|
|
426
|
-
hostKind,
|
|
427
|
-
});
|
|
428
|
-
const allowed = hostKind === 'openclaw'
|
|
429
|
-
? auth.status === 'authorized' || auth.reason === 'consent_missing'
|
|
430
|
-
: auth.status === 'authorized';
|
|
565
|
+
const allowed = isInboxHostAuthorized(input.workspaceDir, hostKind);
|
|
431
566
|
authCache.set(hostKind, allowed);
|
|
432
567
|
return allowed;
|
|
433
568
|
};
|
|
@@ -435,8 +570,8 @@ export function listPainInboxItems(input) {
|
|
|
435
570
|
if (tableExists(db, 'governance_signal_admissions')) {
|
|
436
571
|
const rows = db
|
|
437
572
|
.prepare(`SELECT logical_observation_key, host_kind, root_session_id, signal_kind,
|
|
438
|
-
decision, reason, task_payload_json, created_at
|
|
439
|
-
FROM governance_signal_admissions
|
|
573
|
+
decision, reason, task_payload_json, i.created_at${projectSnooze}
|
|
574
|
+
FROM governance_signal_admissions i ${joinSnoozes("'gsa:' || i.logical_observation_key")}
|
|
440
575
|
WHERE decision IN ('inbox_candidate', 'inbox_approving')
|
|
441
576
|
ORDER BY created_at DESC`)
|
|
442
577
|
.all()
|
|
@@ -451,7 +586,7 @@ export function listPainInboxItems(input) {
|
|
|
451
586
|
continue;
|
|
452
587
|
if (!isHostAuthorized(hostKind))
|
|
453
588
|
continue;
|
|
454
|
-
if (
|
|
589
|
+
if (!visible(row))
|
|
455
590
|
continue;
|
|
456
591
|
const payload = parseJsonSafe(row.task_payload_json);
|
|
457
592
|
const trigger = payload && isRecord(payload.trigger) ? payload.trigger : null;
|
|
@@ -474,7 +609,8 @@ export function listPainInboxItems(input) {
|
|
|
474
609
|
confidence,
|
|
475
610
|
reason: row.reason,
|
|
476
611
|
createdAt: row.created_at,
|
|
477
|
-
expiresAt: computeExpiresAt(row.created_at),
|
|
612
|
+
expiresAt: computeExpiresAt(row.created_at, nowMs, row.review_until),
|
|
613
|
+
snoozedUntil: activeSnoozeUntil(row, nowMs),
|
|
478
614
|
});
|
|
479
615
|
}
|
|
480
616
|
}
|
|
@@ -483,15 +619,15 @@ export function listPainInboxItems(input) {
|
|
|
483
619
|
isHostAuthorized('openclaw') &&
|
|
484
620
|
tableExists(db, 'signal_confirmations')) {
|
|
485
621
|
const rows = db
|
|
486
|
-
.prepare(`SELECT id, session_id, excerpt, resolution, created_at
|
|
487
|
-
FROM signal_confirmations
|
|
622
|
+
.prepare(`SELECT id, session_id, excerpt, resolution, i.created_at${projectSnooze}
|
|
623
|
+
FROM signal_confirmations i ${joinSnoozes("'oc:' || i.id")}
|
|
488
624
|
WHERE status = 'pending'
|
|
489
625
|
AND resolution IN ('inbox_candidate', 'inbox_approving')
|
|
490
626
|
ORDER BY created_at DESC`)
|
|
491
627
|
.all()
|
|
492
628
|
.filter(isOpenClawInboxRow);
|
|
493
629
|
for (const row of rows) {
|
|
494
|
-
if (
|
|
630
|
+
if (!visible(row))
|
|
495
631
|
continue;
|
|
496
632
|
items.push({
|
|
497
633
|
id: `oc:${row.id}`,
|
|
@@ -504,7 +640,8 @@ export function listPainInboxItems(input) {
|
|
|
504
640
|
confidence: null,
|
|
505
641
|
reason: row.resolution,
|
|
506
642
|
createdAt: row.created_at,
|
|
507
|
-
expiresAt: computeExpiresAt(row.created_at),
|
|
643
|
+
expiresAt: computeExpiresAt(row.created_at, nowMs, row.review_until),
|
|
644
|
+
snoozedUntil: activeSnoozeUntil(row, nowMs),
|
|
508
645
|
});
|
|
509
646
|
}
|
|
510
647
|
}
|
|
@@ -514,7 +651,7 @@ export function listPainInboxItems(input) {
|
|
|
514
651
|
codex: items.filter((i) => i.hostKind === 'codex').length,
|
|
515
652
|
workbuddy: items.filter((i) => i.hostKind === 'workbuddy').length,
|
|
516
653
|
};
|
|
517
|
-
return { ok: true, items, total: items.length, byHost };
|
|
654
|
+
return { ok: true, items, total: items.length, snoozedCount, byHost };
|
|
518
655
|
}
|
|
519
656
|
finally {
|
|
520
657
|
close();
|
|
@@ -596,7 +733,7 @@ export async function admitOwnerApprovedInboxCandidate(input) {
|
|
|
596
733
|
if (hostKind !== 'openclaw' && auth.status !== 'authorized') {
|
|
597
734
|
return { ok: true, disposition: 'source_revoked', itemId: input.itemId, reason: auth.reason };
|
|
598
735
|
}
|
|
599
|
-
if (isExpired(row.created_at, nowMs)) {
|
|
736
|
+
if (isExpired(row.created_at, nowMs, readSnooze(db, input.itemId, row.created_at)?.review_until)) {
|
|
600
737
|
return { ok: true, disposition: 'expired', itemId: input.itemId };
|
|
601
738
|
}
|
|
602
739
|
const payload = parseJsonSafe(row.task_payload_json) ?? {};
|
|
@@ -869,7 +1006,7 @@ export async function admitOwnerApprovedInboxCandidate(input) {
|
|
|
869
1006
|
if (ocAuth.status !== 'authorized' && ocAuth.reason !== 'consent_missing') {
|
|
870
1007
|
return { ok: true, disposition: 'source_revoked', itemId: input.itemId, reason: ocAuth.reason };
|
|
871
1008
|
}
|
|
872
|
-
if (isExpired(ocRow.created_at, nowMs)) {
|
|
1009
|
+
if (isExpired(ocRow.created_at, nowMs, readSnooze(db, input.itemId, ocRow.created_at)?.review_until)) {
|
|
873
1010
|
return { ok: true, disposition: 'expired', itemId: input.itemId };
|
|
874
1011
|
}
|
|
875
1012
|
// P2-1: calm neutral correction -> archive as acknowledged_observation
|
|
@@ -1102,23 +1239,34 @@ export function expireStalePainInboxItems(input) {
|
|
|
1102
1239
|
return { ok: true, expiredGsa: 0, expiredOpenClaw: 0 };
|
|
1103
1240
|
const { db, close } = opened;
|
|
1104
1241
|
try {
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1242
|
+
return db.transaction(() => {
|
|
1243
|
+
const hasSnoozes = tableExists(db, SNOOZE_TABLE);
|
|
1244
|
+
const canExpire = (idSql, table) => hasSnoozes
|
|
1245
|
+
? `AND NOT EXISTS (SELECT 1 FROM pain_inbox_snoozes s
|
|
1246
|
+
WHERE s.item_id = ${idSql} AND s.inbox_created_at = ${table}.created_at
|
|
1247
|
+
AND s.review_until > @now)`
|
|
1248
|
+
: '';
|
|
1249
|
+
let expiredGsa = 0;
|
|
1250
|
+
let expiredOpenClaw = 0;
|
|
1251
|
+
if (tableExists(db, 'governance_signal_admissions')) {
|
|
1252
|
+
expiredGsa = db
|
|
1253
|
+
.prepare(`UPDATE governance_signal_admissions
|
|
1254
|
+
SET decision = 'abandoned', reason = 'inbox_ttl_expired', updated_at = @now
|
|
1255
|
+
WHERE decision = 'inbox_candidate' AND created_at <= @cutoff
|
|
1256
|
+
${canExpire("'gsa:' || governance_signal_admissions.logical_observation_key", 'governance_signal_admissions')}`)
|
|
1257
|
+
.run({ now: nowIso, cutoff: cutoffIso }).changes;
|
|
1258
|
+
}
|
|
1259
|
+
if (tableExists(db, 'signal_confirmations')) {
|
|
1260
|
+
expiredOpenClaw = db
|
|
1261
|
+
.prepare(`UPDATE signal_confirmations
|
|
1262
|
+
SET status = 'abandoned', resolution = 'inbox_ttl_expired', resolved_at = @now
|
|
1263
|
+
WHERE status = 'pending' AND resolution = 'inbox_candidate' AND created_at <= @cutoff
|
|
1264
|
+
${canExpire("'oc:' || signal_confirmations.id", 'signal_confirmations')}`)
|
|
1265
|
+
.run({ now: nowIso, cutoff: cutoffIso }).changes;
|
|
1266
|
+
}
|
|
1267
|
+
pruneExpiredSnoozes(db, nowIso);
|
|
1268
|
+
return { ok: true, expiredGsa, expiredOpenClaw };
|
|
1269
|
+
}).immediate();
|
|
1122
1270
|
}
|
|
1123
1271
|
catch (error) {
|
|
1124
1272
|
return {
|