@principles/host-runtime 5.0.0 → 5.2.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/atomic-write-file.d.ts +1 -0
- package/dist/atomic-write-file.js +100 -0
- package/dist/correction-cue-learner.d.ts +69 -0
- package/dist/correction-cue-learner.js +366 -0
- package/dist/correction-observer-config.d.ts +21 -0
- package/dist/correction-observer-config.js +55 -0
- package/dist/correction-observer-cycle.d.ts +33 -0
- package/dist/correction-observer-cycle.js +255 -0
- package/dist/correction-trajectory-reader.d.ts +35 -0
- package/dist/correction-trajectory-reader.js +113 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/internalization-consumer-cycle.js +1 -1
- package/dist/keyword-optimization-service.d.ts +73 -0
- package/dist/keyword-optimization-service.js +265 -0
- package/dist/pain-inbox.d.ts +28 -0
- package/dist/pain-inbox.js +194 -46
- package/dist/signal-health.d.ts +54 -0
- package/dist/signal-health.js +194 -0
- package/dist/workspace-pipeline-host-deps.d.ts +2 -0
- package/dist/workspace-pipeline-host-deps.js +1 -1
- package/package.json +7 -3
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 {
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
declare const CORRECTION_OBSERVER_HOSTS: readonly ['openclaw', 'codex', 'workbuddy'];
|
|
2
|
+
export type CorrectionObserverHostKind = typeof CORRECTION_OBSERVER_HOSTS[number];
|
|
3
|
+
type ObserverInputDigests = Partial<Record<CorrectionObserverHostKind, string>>;
|
|
4
|
+
export interface SignalHealthState {
|
|
5
|
+
/** 当日计数:跨日首写归零 */
|
|
6
|
+
stage1Strong: number;
|
|
7
|
+
stage2Confirmed: number;
|
|
8
|
+
stage2Queued: number;
|
|
9
|
+
stage2Dropped: number;
|
|
10
|
+
/**
|
|
11
|
+
* AUDIT-P2-02 (2026-10-21): 当日实际发起的 Stage2 LLM 分类调用次数
|
|
12
|
+
* (realtime detectAsyncAndRoute + 批量确认 confirmPendingSignal 都算——
|
|
13
|
+
* 两者都是花同一个 signal classifier 的钱)。计数时点:真正发起 classifier
|
|
14
|
+
* 调用前;降级/空队列/未配置不计数。跨日归零;旧文件缺失按 0 读。
|
|
15
|
+
*/
|
|
16
|
+
stage2Invocations: number;
|
|
17
|
+
/**
|
|
18
|
+
* AUDIT-P2-02 (2026-10-21): 当日因分类器不可用被整批跳过的批量确认次数。
|
|
19
|
+
* 只在「队列非空但 classifier 解析失败」时 +1(空队列不计数——没有工作被
|
|
20
|
+
* 跳过)。让 Owner 能区分「没检测到信号 / 没调用模型 / 队列没被消费」。
|
|
21
|
+
* 跨日归零;旧文件缺失按 0 读。
|
|
22
|
+
*/
|
|
23
|
+
stage2BatchSkipped: number;
|
|
24
|
+
/**
|
|
25
|
+
* 零命中「发现」调用被每小时配额挡下的次数(AUDIT-P2-03 性能整改)。
|
|
26
|
+
* 它回答「有多少普通消息本来要送去分类、被预算拦住了」——没有这个计数,
|
|
27
|
+
* 调用量下降就无法与「检测失效」区分。跨日归零;旧文件缺失按 0 读。
|
|
28
|
+
*/
|
|
29
|
+
stage2DiscoverySkipped: number;
|
|
30
|
+
/** 最近一次刷新的队列深度(非计数) */
|
|
31
|
+
pendingCount: number;
|
|
32
|
+
lastStage2SuccessAt: string | null;
|
|
33
|
+
/** The shared cooldown clock, not an input watermark. */
|
|
34
|
+
observerLastSuccessAt: string | null;
|
|
35
|
+
/** One digest per host of its last successfully processed, bounded input. No transcript text. */
|
|
36
|
+
observerInputDigests?: ObserverInputDigests;
|
|
37
|
+
/** observer 周期连续失败次数(成功即归零) */
|
|
38
|
+
observerConsecutiveFailures: number;
|
|
39
|
+
/** 归零基准日(YYYY-MM-DD) */
|
|
40
|
+
day: string;
|
|
41
|
+
updatedAt: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 读健康状态(doctor 用)。文件缺失/损坏返回 null,由读取方呈现 unknown。
|
|
45
|
+
* 旧格式(无 AUDIT-P2-02 新增计数字段)照常解析,缺省字段读作 0。
|
|
46
|
+
*/
|
|
47
|
+
export declare function readSignalHealth(stateDir: string): SignalHealthState | null;
|
|
48
|
+
/**
|
|
49
|
+
* 原子更新健康状态。mutator 收到当前状态(已做跨日归零),就地修改后写回。
|
|
50
|
+
* 任何失败都不抛出——旁路观测不阻塞检测管线。
|
|
51
|
+
*/
|
|
52
|
+
export type SignalHealthWriteError = (workspaceDir: string, error: unknown) => void;
|
|
53
|
+
export declare function updateSignalHealth(stateDir: string, mutate: (state: SignalHealthState) => void, onError?: SignalHealthWriteError): void;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-788 G4: 纠正信号检测健康度产物。
|
|
3
|
+
*
|
|
4
|
+
* 背景:检测器停摆 5 天 409 次失败只进 7 天滚动的 SYSTEM log(ERR-101 家族),
|
|
5
|
+
* Owner 无从发现。本模块把检测链路的关键计数/时间戳原子写入
|
|
6
|
+
* `<workspace>/.state/signal-health.json`,供 `pd config doctor` 呈现。
|
|
7
|
+
*
|
|
8
|
+
* 契约:
|
|
9
|
+
* - 当日计数(stage1Strong/stage2Confirmed/stage2Queued/stage2Dropped/
|
|
10
|
+
* stage2Invocations/stage2BatchSkipped/stage2DiscoverySkipped)在跨日首次写入时归零;
|
|
11
|
+
* 时间戳字段为绝对 ISO 值。
|
|
12
|
+
* - 写失败绝不抛出(健康度是旁路观测,不阻塞检测管线)——通知宿主的可选错误处理(rc-9)。
|
|
13
|
+
* - 文件缺失/损坏按默认值重建,读取方(doctor)自行 unknown 呈现。
|
|
14
|
+
* - AUDIT-P2-02:stage2Invocations/stage2BatchSkipped 为新增字段,升级前的
|
|
15
|
+
* 旧文件缺这两个键仍合法(读作 0);写路径始终写入完整新格式。
|
|
16
|
+
* - 所有 I/O 路径先经 guardWorkspaceLeak:测试里 mock 的 '/fake/state' 在
|
|
17
|
+
* Windows 会被 resolve 成盘根 D:\fake\state,必须和其它 I/O 入口一样重定向
|
|
18
|
+
* 到 os.tmpdir(),否则每次跑测试都在文件系统根重建目录(含 mkdir)。
|
|
19
|
+
*/
|
|
20
|
+
import * as fs from 'fs';
|
|
21
|
+
import * as path from 'path';
|
|
22
|
+
import { atomicWriteFileSync } from './atomic-write-file.js';
|
|
23
|
+
import { guardWorkspaceLeak } from '@principles/core/runtime/store/workspace-leak-guard';
|
|
24
|
+
const SIGNAL_HEALTH_FILE = 'signal-health.json';
|
|
25
|
+
const CORRECTION_OBSERVER_HOSTS = ['openclaw', 'codex', 'workbuddy'];
|
|
26
|
+
function parseObserverInputDigests(value) {
|
|
27
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
28
|
+
return undefined;
|
|
29
|
+
const state = value;
|
|
30
|
+
const digests = {};
|
|
31
|
+
for (const hostKind of CORRECTION_OBSERVER_HOSTS) {
|
|
32
|
+
const digest = Object.hasOwn(state, hostKind) ? state[hostKind] : undefined;
|
|
33
|
+
if (typeof digest === 'string' && /^[a-f0-9]{64}$/.test(digest))
|
|
34
|
+
digests[hostKind] = digest;
|
|
35
|
+
}
|
|
36
|
+
return Object.keys(digests).length > 0 ? digests : undefined;
|
|
37
|
+
}
|
|
38
|
+
function defaultState(now) {
|
|
39
|
+
return {
|
|
40
|
+
stage1Strong: 0,
|
|
41
|
+
stage2Confirmed: 0,
|
|
42
|
+
stage2Queued: 0,
|
|
43
|
+
stage2Dropped: 0,
|
|
44
|
+
stage2Invocations: 0,
|
|
45
|
+
stage2BatchSkipped: 0,
|
|
46
|
+
stage2DiscoverySkipped: 0,
|
|
47
|
+
pendingCount: 0,
|
|
48
|
+
lastStage2SuccessAt: null,
|
|
49
|
+
observerLastSuccessAt: null,
|
|
50
|
+
observerConsecutiveFailures: 0,
|
|
51
|
+
day: now.toISOString().slice(0, 10),
|
|
52
|
+
updatedAt: now.toISOString(),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function healthFilePath(stateDir) {
|
|
56
|
+
return path.join(stateDir, SIGNAL_HEALTH_FILE);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 结构校验 + 解析:只接受带全部必需数值/字符串字段的对象(ERR-001/ERR-013),
|
|
60
|
+
* 并逐字段构造出完整的 SignalHealthState。
|
|
61
|
+
* 用 Object.hasOwn + typeof 做运行时收窄,避免 `in` 命中原型链、
|
|
62
|
+
* 也避免 `as` 把未校验数据直接断言成领域类型。
|
|
63
|
+
*
|
|
64
|
+
* AUDIT-P2-02 向后兼容规则:stage2Invocations / stage2BatchSkipped 是新增
|
|
65
|
+
* 字段——升级前的旧健康文件没有它们,必须照常解析(缺省读作 0),
|
|
66
|
+
* 否则升级会让 doctor 从「有计数」退化成 unknown。字段存在时仍必须是 number。
|
|
67
|
+
*/
|
|
68
|
+
function parseSignalHealthState(value) {
|
|
69
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const obj = value;
|
|
73
|
+
const requiredNum = (key) => {
|
|
74
|
+
if (!Object.hasOwn(obj, key))
|
|
75
|
+
return null;
|
|
76
|
+
const v = obj[key];
|
|
77
|
+
return typeof v === 'number' ? v : null;
|
|
78
|
+
};
|
|
79
|
+
const optionalNum = (key) => {
|
|
80
|
+
const v = obj[key];
|
|
81
|
+
return typeof v === 'number' ? v : 0;
|
|
82
|
+
};
|
|
83
|
+
const optionalStr = (key) => {
|
|
84
|
+
const v = obj[key];
|
|
85
|
+
return typeof v === 'string' ? v : null;
|
|
86
|
+
};
|
|
87
|
+
const stage1Strong = requiredNum('stage1Strong');
|
|
88
|
+
const stage2Confirmed = requiredNum('stage2Confirmed');
|
|
89
|
+
const stage2Queued = requiredNum('stage2Queued');
|
|
90
|
+
const stage2Dropped = requiredNum('stage2Dropped');
|
|
91
|
+
const pendingCount = requiredNum('pendingCount');
|
|
92
|
+
const observerConsecutiveFailures = requiredNum('observerConsecutiveFailures');
|
|
93
|
+
const day = optionalStr('day');
|
|
94
|
+
const updatedAt = optionalStr('updatedAt');
|
|
95
|
+
if (stage1Strong === null || stage2Confirmed === null || stage2Queued === null ||
|
|
96
|
+
stage2Dropped === null || pendingCount === null || observerConsecutiveFailures === null ||
|
|
97
|
+
day === null || updatedAt === null) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
// 新字段存在但非数值 → 视为损坏(与旧必需字段同一纪律)。
|
|
101
|
+
if (Object.hasOwn(obj, 'stage2Invocations') && typeof obj.stage2Invocations !== 'number')
|
|
102
|
+
return null;
|
|
103
|
+
if (Object.hasOwn(obj, 'stage2BatchSkipped') && typeof obj.stage2BatchSkipped !== 'number')
|
|
104
|
+
return null;
|
|
105
|
+
if (Object.hasOwn(obj, 'stage2DiscoverySkipped') && typeof obj.stage2DiscoverySkipped !== 'number')
|
|
106
|
+
return null;
|
|
107
|
+
const digests = parseObserverInputDigests(obj.observerInputDigests);
|
|
108
|
+
return {
|
|
109
|
+
stage1Strong,
|
|
110
|
+
stage2Confirmed,
|
|
111
|
+
stage2Queued,
|
|
112
|
+
stage2Dropped,
|
|
113
|
+
stage2Invocations: optionalNum('stage2Invocations'),
|
|
114
|
+
stage2BatchSkipped: optionalNum('stage2BatchSkipped'),
|
|
115
|
+
stage2DiscoverySkipped: optionalNum('stage2DiscoverySkipped'),
|
|
116
|
+
pendingCount,
|
|
117
|
+
lastStage2SuccessAt: optionalStr('lastStage2SuccessAt'),
|
|
118
|
+
observerLastSuccessAt: optionalStr('observerLastSuccessAt'),
|
|
119
|
+
...(digests === undefined ? {} : { observerInputDigests: digests }),
|
|
120
|
+
observerConsecutiveFailures,
|
|
121
|
+
day,
|
|
122
|
+
updatedAt,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function loadState(stateDir, now) {
|
|
126
|
+
try {
|
|
127
|
+
const raw = fs.readFileSync(healthFilePath(stateDir), 'utf-8');
|
|
128
|
+
const parsed = JSON.parse(raw);
|
|
129
|
+
const state = parseSignalHealthState(parsed);
|
|
130
|
+
if (state) {
|
|
131
|
+
const today = now.toISOString().slice(0, 10);
|
|
132
|
+
if (state.day !== today) {
|
|
133
|
+
// 跨日:当日计数归零(含 AUDIT-P2-02 新增计数),时间戳与失败计数保留
|
|
134
|
+
return {
|
|
135
|
+
...state,
|
|
136
|
+
stage1Strong: 0,
|
|
137
|
+
stage2Confirmed: 0,
|
|
138
|
+
stage2Queued: 0,
|
|
139
|
+
stage2Dropped: 0,
|
|
140
|
+
stage2Invocations: 0,
|
|
141
|
+
stage2BatchSkipped: 0,
|
|
142
|
+
stage2DiscoverySkipped: 0,
|
|
143
|
+
day: today,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return state;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// 缺失/损坏 → 重建默认值(doctor 侧以 updatedAt/字段存在性呈现 unknown)
|
|
151
|
+
}
|
|
152
|
+
return defaultState(now);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* 读健康状态(doctor 用)。文件缺失/损坏返回 null,由读取方呈现 unknown。
|
|
156
|
+
* 旧格式(无 AUDIT-P2-02 新增计数字段)照常解析,缺省字段读作 0。
|
|
157
|
+
*/
|
|
158
|
+
export function readSignalHealth(stateDir) {
|
|
159
|
+
try {
|
|
160
|
+
const raw = fs.readFileSync(healthFilePath(guardWorkspaceLeak(stateDir)), 'utf-8');
|
|
161
|
+
const parsed = JSON.parse(raw);
|
|
162
|
+
return parseSignalHealthState(parsed);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
export function updateSignalHealth(stateDir, mutate, onError) {
|
|
169
|
+
// Guard BEFORE the mkdir — a leaked '/fake/state' must not recreate
|
|
170
|
+
// D:\fake\state on Windows. loadState / healthFilePath receive the same
|
|
171
|
+
// guarded dir, so read and write always agree on one location.
|
|
172
|
+
const safeStateDir = guardWorkspaceLeak(stateDir);
|
|
173
|
+
try {
|
|
174
|
+
const now = new Date();
|
|
175
|
+
const state = loadState(safeStateDir, now);
|
|
176
|
+
mutate(state);
|
|
177
|
+
state.updatedAt = now.toISOString();
|
|
178
|
+
state.day = now.toISOString().slice(0, 10);
|
|
179
|
+
fs.mkdirSync(safeStateDir, { recursive: true });
|
|
180
|
+
atomicWriteFileSync(healthFilePath(safeStateDir), JSON.stringify(state, null, 2));
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
// Without a concrete workspace, do not write an audit line to cwd.
|
|
184
|
+
// Reporting is best-effort too: an optional host callback cannot block detection.
|
|
185
|
+
if (safeStateDir) {
|
|
186
|
+
try {
|
|
187
|
+
onError?.(path.dirname(safeStateDir), err);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// The health write has already failed; keep the side channel non-blocking.
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -45,6 +45,8 @@ export interface ResolveWorkspacePipelineHostDepsInput {
|
|
|
45
45
|
readonly workspaceDir: string;
|
|
46
46
|
/** The CURRENT entry's effective config — the intent reader's flag authority (SPEC §13.1). */
|
|
47
47
|
readonly effectiveConfig: EffectivePdConfig;
|
|
48
|
+
/** Reuse the worker cycle's workspace-scoped, live consent port. */
|
|
49
|
+
readonly sourceMaterialAuthorization?: SourceMaterialAuthorizationPort;
|
|
48
50
|
/**
|
|
49
51
|
* OpenClaw Gateway hook / command processes already hold
|
|
50
52
|
* `WorkspaceContext.trajectory`; pass it here to replace the default
|
|
@@ -57,7 +57,7 @@ export function resolveWorkspacePipelineHostDeps(input) {
|
|
|
57
57
|
// trajectory reader and every gate consumer returned to the caller observe
|
|
58
58
|
// the SAME latest-consent state (the double-instance defect this module
|
|
59
59
|
// exists to remove).
|
|
60
|
-
const sourceMaterialAuthorization = createConsentLedgerSourceMaterialAuthorization(input.workspaceDir);
|
|
60
|
+
const sourceMaterialAuthorization = input.sourceMaterialAuthorization ?? createConsentLedgerSourceMaterialAuthorization(input.workspaceDir);
|
|
61
61
|
const overrideHostKind = input.trajectoryTurnReaderOverrideHostKind;
|
|
62
62
|
if (input.trajectoryTurnReaderOverride !== undefined && overrideHostKind === undefined) {
|
|
63
63
|
throw new Error('trajectoryTurnReaderOverrideHostKind is required when trajectoryTurnReaderOverride is provided');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.2.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
"default": "./dist/index.js"
|
|
12
12
|
},
|
|
13
13
|
"./package.json": "./package.json",
|
|
14
|
+
"./atomic-write-file": {
|
|
15
|
+
"types": "./dist/atomic-write-file.d.ts",
|
|
16
|
+
"default": "./dist/atomic-write-file.js"
|
|
17
|
+
},
|
|
14
18
|
"./behavior-example-pack-assembler": {
|
|
15
19
|
"types": "./dist/behavior-example-pack-assembler.d.ts",
|
|
16
20
|
"default": "./dist/behavior-example-pack-assembler.js"
|
|
@@ -39,7 +43,7 @@
|
|
|
39
43
|
"lint": "eslint \"src/**/*.ts\""
|
|
40
44
|
},
|
|
41
45
|
"dependencies": {
|
|
42
|
-
"@principles/core": "^
|
|
46
|
+
"@principles/core": "^11.0.0",
|
|
43
47
|
"@principles/install-layout": "^0.12.0",
|
|
44
48
|
"better-sqlite3": "^13.0.3",
|
|
45
49
|
"js-yaml": "^5.4.3"
|
|
@@ -57,5 +61,5 @@
|
|
|
57
61
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
58
62
|
},
|
|
59
63
|
"license": "Apache-2.0",
|
|
60
|
-
"gitHead": "
|
|
64
|
+
"gitHead": "549a73b98fcbf19100938c24c3163f811bbf50bd"
|
|
61
65
|
}
|