principles-disciple 1.149.0 → 1.150.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/README.md CHANGED
@@ -25,7 +25,6 @@ All commands support **short aliases** for easier input:
25
25
  | `/pdb` | `/pd-bootstrap` | Scan environment tools |
26
26
  | `/pdr` | `/pd-research` | Research tools and capabilities |
27
27
  | `/pdt` | `/pd-thinking` | Manage thinking models |
28
- | `/pdrl` | `/pd-reflect` | Manually trigger nocturnal reflection |
29
28
  | `/pdd` | `/pd-daily` | Configure and send daily report |
30
29
  | `/pdg` | `/pd-grooming` | Workspace cleanup |
31
30
  | `/pdh` | `/pd-help` | Show command reference |
@@ -39,9 +38,6 @@ All commands support **short aliases** for easier input:
39
38
  | `/pd-rollback` | Rollback to previous state |
40
39
  | `/pd-export` | Export trajectory/correction data |
41
40
  | `/pd-samples` | Review correction samples |
42
- | `/pd-nocturnal-review` | Review nocturnal training samples |
43
- | `/nocturnal-train` | Nocturnal training operations |
44
- | `/nocturnal-rollout` | Nocturnal rollout and promotion |
45
41
  | `/pd-workflow-debug` | Debug workflow state |
46
42
 
47
43
  ### Configuration
@@ -69,8 +69,6 @@ export class EventLog {
69
69
  recordPainSignal(sessionId, data) {
70
70
  this.record('pain_signal', 'detected', sessionId, data);
71
71
  }
72
- // recordRuleMatch removed (PRI-451 Wave 1): dead code. Its only effect was
73
- // incrementing stats.pain.rulesMatched (also dead, removed in Wave 1.5).
74
72
  recordRulePromotion(data) {
75
73
  this.record('rule_promotion', 'promoted', undefined, data);
76
74
  }
@@ -350,9 +348,6 @@ export class EventLog {
350
348
  stats.empathy.rollbackCount++;
351
349
  stats.empathy.rolledBackScore += data.originalScore || 0;
352
350
  }
353
- // rule_match handler removed (PRI-451 Wave 1.5): recordRuleMatch is gone
354
- // (Wave 1.1), so no rule_match events are emitted; stats.pain.rulesMatched
355
- // was its only consumer and is also removed.
356
351
  else if (entry.type === 'rule_promotion') {
357
352
  // stats.pain.candidatesPromoted removed (PRI-451 Wave 1.5): dead counter.
358
353
  stats.evolution.rulesPromoted++;
@@ -16,7 +16,7 @@ function pushWarning(warnings, message) {
16
16
  }
17
17
  }
18
18
  /**
19
- * YAML-SSOT-03: resolve a dot-path (e.g. 'evolution.nocturnalDreamerCompleted') from dailyStats.
19
+ * YAML-SSOT-03: resolve a dot-path (e.g. 'evolution.rulehostEvaluated') from dailyStats.
20
20
  * Returns { count, resolvable } to distinguish "field not found / non-numeric" from "legitimate zero".
21
21
  */
22
22
  function resolveStatsField(stats, dotPath) {
@@ -1,2 +1,2 @@
1
- export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RuleMatchEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuleHostUnhealthyEventData, ToolCallStats, ErrorStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
1
+ export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuleHostUnhealthyEventData, ToolCallStats, ErrorStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
2
2
  export { createEmptyDailyStats, } from '@principles/core/runtime-v2';
@@ -2,7 +2,7 @@
2
2
  "id": "principles-disciple",
3
3
  "name": "Principles Disciple",
4
4
  "description": "Evolutionary programming agent framework with strategic guardrails and reflection loops.",
5
- "version": "1.149.0",
5
+ "version": "1.150.0",
6
6
  "activation": {
7
7
  "onCapabilities": [
8
8
  "hook"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "principles-disciple",
3
- "version": "1.149.0",
3
+ "version": "1.150.0",
4
4
  "description": "Native OpenClaw plugin for Principles Disciple",
5
5
  "type": "module",
6
6
  "main": "./dist/bundle.js",
@@ -47,7 +47,6 @@
47
47
  "lint": "eslint \"src/**/*.ts\"",
48
48
  "bootstrap-rules": "node scripts/bootstrap-rules.mjs",
49
49
  "compile-principles": "node scripts/compile-principles.mjs",
50
- "validate-live-path": "tsx scripts/validate-live-path.ts",
51
50
  "sync-plugin": "node scripts/sync-plugin.mjs"
52
51
  },
53
52
  "devDependencies": {
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * Nocturnal Pipeline — End-to-End Acceptance Test
4
+ * PD Pipeline — End-to-End Acceptance Test
5
5
  *
6
- * Verifies that all components of the Nocturnal reflection pipeline
6
+ * Verifies that all components of the PD reflection pipeline
7
7
  * work correctly in a real environment (not unit tests).
8
8
  *
9
9
  * Usage:
@@ -71,7 +71,7 @@ function main() {
71
71
  process.exit(1);
72
72
  }
73
73
 
74
- console.log('\n🧪 Nocturnal Pipeline Acceptance Test');
74
+ console.log('\n🧪 PD Pipeline Acceptance Test');
75
75
  console.log('═'.repeat(55));
76
76
  console.log(`Workspace: ${workspaceDir}`);
77
77
  console.log(`Database: ${dbPath}\n`);
@@ -1,462 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Validate Live Path Script (Phase 18) — with Data Flow Monitoring
4
- *
5
- * Validates the end-to-end nocturnal workflow path with bootstrapped principles.
6
- *
7
- * Purpose:
8
- * - Reads bootstrapped rules from principle_training_state.json
9
- * - Creates synthetic snapshot with recentPain to pass hasUsableNocturnalSnapshot() guard
10
- * - Enqueues sleep_reflection task with proper file locking
11
- * - Polls subagent_workflows.db directly for nocturnal workflows
12
- * - Correlates workflow to queue item via taskId
13
- * - Verifies state='completed' and explicit resolution (not 'expired')
14
- * - Monitors data flow: queue state → workflow state → artifact persistence
15
- * - Outputs summary and exits 0 on success, non-zero on failure
16
- *
17
- * Usage:
18
- * tsx scripts/validate-live-path.ts [--verbose]
19
- *
20
- * Environment:
21
- * WORKSPACE_DIR - Optional workspace directory (defaults to process.cwd())
22
- */
23
-
24
- import * as Database from 'better-sqlite3';
25
- import * as fs from 'fs';
26
- import * as path from 'path';
27
-
28
- // ─── Constants ───────────────────────────────────────────────────────────
29
- const POLL_INTERVAL_MS = 5_000;
30
- const POLL_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
31
- const LOCK_SUFFIX = '.lock';
32
- const LOCK_MAX_RETRIES = 50;
33
- const LOCK_RETRY_DELAY_MS = 50;
34
- const LOCK_STALE_MS = 30_000;
35
- const WORKSPACE_DIR = process.env.WORKSPACE_DIR || process.cwd();
36
- const STATE_DIR = path.join(WORKSPACE_DIR, '.state');
37
- const QUEUE_PATH = path.join(STATE_DIR, 'EVOLUTION_QUEUE');
38
- const LEDGER_PATH = path.join(STATE_DIR, 'principle_training_state.json');
39
- const DB_PATH = path.join(STATE_DIR, 'subagent_workflows.db');
40
- const SAMPLES_DIR = path.join(STATE_DIR, 'nocturnal', 'samples');
41
-
42
- // ─── Helpers ─────────────────────────────────────────────────────────────
43
- function timestamp(): string {
44
- return new Date().toISOString();
45
- }
46
-
47
- function logStep(step: string, detail: string): void {
48
- console.log(`[${timestamp()}] ▸ ${step}: ${detail}`);
49
- }
50
-
51
- function logData(label: string, data: unknown): void {
52
- const display = typeof data === 'string' ? data : JSON.stringify(data).slice(0, 300);
53
- console.log(`[${timestamp()}] 📦 ${label}: ${display}`);
54
- }
55
-
56
- function safeReadJson(filePath: string): unknown {
57
- try {
58
- if (!fs.existsSync(filePath)) return null;
59
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
60
- } catch { return null; }
61
- }
62
-
63
- // ─── Types ───────────────────────────────────────────────────────────────
64
- interface LedgerRule {
65
- id: string;
66
- principleId: string;
67
- action: string;
68
- type: string;
69
- }
70
-
71
- interface HybridLedgerStore {
72
- tree: {
73
- rules: Record<string, LedgerRule>;
74
- };
75
- }
76
-
77
- interface WorkflowRow {
78
- workflow_id: string;
79
- workflow_type: string;
80
- state: string;
81
- metadata_json: string;
82
- created_at: number;
83
- }
84
-
85
- interface QueueItem {
86
- id: string;
87
- taskKind: string;
88
- status: string;
89
- resolution?: string;
90
- resultRef?: string;
91
- }
92
-
93
- interface LockContext {
94
- lockPath: string;
95
- pid: number;
96
- release: () => void;
97
- }
98
-
99
- // ─── File Lock Functions (simplified from file-lock.ts) ──────────────────
100
- async function acquireLockAsync(filePath: string, options: {
101
- lockSuffix?: string;
102
- maxRetries?: number;
103
- baseRetryDelayMs?: number;
104
- lockStaleMs?: number;
105
- } = {}): Promise<LockContext> {
106
- const lockSuffix = options.lockSuffix ?? LOCK_SUFFIX;
107
- const maxRetries = options.maxRetries ?? LOCK_MAX_RETRIES;
108
- const baseRetryDelayMs = options.baseRetryDelayMs ?? LOCK_RETRY_DELAY_MS;
109
- const lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS;
110
- const { pid } = process;
111
- const lockPath = filePath + lockSuffix;
112
-
113
- for (let attempt = 0; attempt < maxRetries; attempt++) {
114
- try {
115
- // Check if lock file exists and is stale
116
- if (fs.existsSync(lockPath)) {
117
- const lockContent = fs.readFileSync(lockPath, 'utf8');
118
- const lockPid = parseInt(lockContent, 10);
119
- const lockStats = fs.statSync(lockPath);
120
- const lockAge = Date.now() - lockStats.mtimeMs;
121
-
122
- // Clean up stale lock
123
- if (lockAge > lockStaleMs) {
124
- fs.unlinkSync(lockPath);
125
- } else if (lockPid !== pid) {
126
- // Lock held by another process
127
- await new Promise(resolve => setTimeout(resolve, baseRetryDelayMs));
128
- continue;
129
- }
130
- }
131
-
132
- // Acquire lock
133
- fs.writeFileSync(lockPath, pid.toString(), { flag: 'wx' });
134
- return {
135
- lockPath,
136
- pid,
137
- release: () => {
138
- try {
139
- if (fs.existsSync(lockPath)) {
140
- fs.unlinkSync(lockPath);
141
- }
142
- } catch {
143
- // Ignore errors during release
144
- }
145
- },
146
- };
147
- } catch (error: unknown) {
148
- const err = error as { code?: string };
149
- if (err.code === 'EEXIST') {
150
- if (attempt < maxRetries - 1) {
151
- await new Promise(resolve => setTimeout(resolve, baseRetryDelayMs));
152
- continue;
153
- }
154
- }
155
- const lockError = new Error(`Failed to acquire lock for ${filePath}: ${String(error)}`);
156
- lockError.cause = error;
157
- throw lockError;
158
- }
159
- }
160
-
161
- throw new Error(`Failed to acquire lock for ${filePath} after ${maxRetries} attempts`);
162
- }
163
-
164
- function releaseLock(ctx: LockContext): void {
165
- ctx.release();
166
- }
167
-
168
- // ─── Step 1: Check bootstrapped rules ─────────────────────────────────────
169
- function loadBootstrappedRules(): LedgerRule[] {
170
- if (!fs.existsSync(LEDGER_PATH)) {
171
- throw new Error('FAIL: principle_training_state.json not found. Run Phase 17 bootstrap first: npm run bootstrap-rules');
172
- }
173
-
174
- const ledger: HybridLedgerStore = JSON.parse(fs.readFileSync(LEDGER_PATH, 'utf8'));
175
- const bootstrappedRules = Object.values(ledger.tree.rules).filter(r =>
176
- r.id.endsWith('_stub_bootstrap')
177
- );
178
-
179
- return bootstrappedRules;
180
- }
181
-
182
- // ─── Step 2: Build synthetic snapshot ──────────────────────────────────────
183
- function buildSyntheticSnapshot(taskId: string) {
184
- return {
185
- sessionId: `validation-${taskId}`,
186
- startedAt: new Date().toISOString(),
187
- updatedAt: new Date().toISOString(),
188
- assistantTurns: [],
189
- userTurns: [],
190
- toolCalls: [],
191
- painEvents: [],
192
- gateBlocks: [],
193
- stats: {
194
- totalAssistantTurns: 0,
195
- totalToolCalls: 0,
196
- failureCount: 0,
197
- totalPainEvents: 1,
198
- totalGateBlocks: 0,
199
- },
200
- recentPain: [{
201
- source: 'live-validation',
202
- score: 50,
203
- severity: 'moderate',
204
- reason: 'Synthetic snapshot for live path validation',
205
- createdAt: new Date().toISOString(),
206
- }],
207
- _dataSource: 'pain_context_fallback',
208
- };
209
- }
210
-
211
- // ─── Step 3: Enqueue sleep_reflection task with proper file locking ──────────
212
- // Uses acquireLockAsync to prevent TOCTOU race conditions (T-18-01 mitigation)
213
- async function enqueueSleepReflectionTask(taskId: string): Promise<void> {
214
- let lockCtx: LockContext | null = null;
215
- try {
216
- // Acquire lock before reading queue file (T-18-01 mitigation)
217
- lockCtx = await acquireLockAsync(QUEUE_PATH, {
218
- lockSuffix: LOCK_SUFFIX,
219
- maxRetries: LOCK_MAX_RETRIES,
220
- baseRetryDelayMs: LOCK_RETRY_DELAY_MS,
221
- lockStaleMs: LOCK_STALE_MS,
222
- });
223
-
224
- let queue: QueueItem[] = [];
225
- if (fs.existsSync(QUEUE_PATH)) {
226
- const queueContent = fs.readFileSync(QUEUE_PATH, 'utf8');
227
- queue = JSON.parse(queueContent);
228
- }
229
-
230
- queue.push({
231
- id: taskId,
232
- taskKind: 'sleep_reflection',
233
- status: 'pending',
234
- });
235
-
236
- fs.writeFileSync(QUEUE_PATH, JSON.stringify(queue, null, 2), 'utf8');
237
- } finally {
238
- if (lockCtx) {
239
- releaseLock(lockCtx);
240
- }
241
- }
242
- }
243
-
244
- // ─── Step 4: Poll workflow store (raw SQLite, no WorkflowStore import) ─────
245
- // Uses better-sqlite3 directly to avoid WorkflowStore async initialization issues in standalone script
246
- function listNocturnalWorkflows(): WorkflowRow[] {
247
- if (!fs.existsSync(DB_PATH)) {
248
- return [];
249
- }
250
-
251
- const db = new Database(DB_PATH, { readonly: true });
252
- const rows = db.prepare(`
253
- SELECT workflow_id, workflow_type, state, metadata_json, created_at
254
- FROM subagent_workflows
255
- WHERE workflow_type = 'nocturnal'
256
- ORDER BY created_at DESC
257
- `).all() as WorkflowRow[];
258
- db.close();
259
- return rows;
260
- }
261
-
262
- // ─── Step 5: Correlate and verify ─────────────────────────────────────────
263
- function verifyWorkflowCompletion(taskId: string): {
264
- workflowId: string;
265
- state: string;
266
- resolution: string;
267
- } | null {
268
- const workflows = listNocturnalWorkflows();
269
-
270
- for (const wf of workflows) {
271
- const meta = JSON.parse(wf.metadata_json);
272
- if (meta.taskId !== taskId) continue;
273
- if (wf.state !== 'completed') continue;
274
-
275
- // Read resolution from queue (resolution is on queue item, not on WorkflowRow)
276
- let queue: QueueItem[] = [];
277
- try {
278
- if (fs.existsSync(QUEUE_PATH)) {
279
- const queueContent = fs.readFileSync(QUEUE_PATH, 'utf8');
280
- queue = JSON.parse(queueContent);
281
- }
282
- } catch {
283
- // Queue file missing or corrupted — resolution unknown
284
- }
285
-
286
- const queueItem = queue.find(q => q.id === taskId);
287
- const resolution = queueItem?.resolution;
288
-
289
- return {
290
- workflowId: wf.workflow_id,
291
- state: wf.state,
292
- resolution: resolution || 'MISSING',
293
- };
294
- }
295
-
296
- return null;
297
- }
298
-
299
- // ─── Main ─────────────────────────────────────────────────────────────────
300
- async function main() {
301
- const verbose = process.argv.includes('--verbose');
302
-
303
- console.log('╔══════════════════════════════════════════════════════════╗');
304
- console.log('║ Nocturnal Live Path Validation + Data Flow Monitor ║');
305
- console.log('╚══════════════════════════════════════════════════════════╝');
306
- logStep('WORKSPACE', WORKSPACE_DIR);
307
-
308
- // 0. Baseline: snapshot current state
309
- logStep('BASELINE', 'Capturing current state before validation');
310
- const queueBefore = safeReadJson(QUEUE_PATH) as QueueItem[] | null;
311
- logData('EVOLUTION_QUEUE (before)', queueBefore?.length ?? 0);
312
- if (fs.existsSync(SAMPLES_DIR)) {
313
- const samplesBefore = fs.readdirSync(SAMPLES_DIR).length;
314
- logData('nocturnal/samples/', `${samplesBefore} files`);
315
- } else {
316
- logData('nocturnal/samples/', 'directory not present');
317
- }
318
- if (fs.existsSync(DB_PATH)) {
319
- const wfCount = listNocturnalWorkflows().length;
320
- logData('subagent_workflows.db', `${wfCount} nocturnal workflows`);
321
- } else {
322
- logData('subagent_workflows.db', 'not present');
323
- }
324
-
325
- // 1. Check bootstrapped rules
326
- // eslint-disable-next-line @typescript-eslint/init-declarations
327
- let rules: LedgerRule[];
328
- try {
329
- rules = loadBootstrappedRules();
330
- logStep('STEP 1', `Found ${rules.length} bootstrapped rule(s)`);
331
- } catch {
332
- console.error('FAIL: principle_training_state.json not found. Run Phase 17 bootstrap first: npm run bootstrap-rules');
333
- process.exit(1);
334
- }
335
-
336
- if (rules.length === 0) {
337
- console.error('FAIL: No _stub_bootstrap rules found. Run Phase 17 bootstrap first: npm run bootstrap-rules');
338
- process.exit(1);
339
- }
340
-
341
- if (verbose) {
342
- for (const rule of rules) {
343
- console.log(` - ${rule.id} (principleId=${rule.principleId}, action=${rule.action})`);
344
- }
345
- }
346
-
347
- // 2. Generate task ID
348
- const taskId = `validation-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
349
-
350
- // 3. Build synthetic snapshot for validation
351
- const snapshot = buildSyntheticSnapshot(taskId);
352
- logStep('STEP 2', `Synthetic snapshot: sessionId=${snapshot.sessionId}`);
353
- logData('snapshot.recentPain', JSON.stringify(snapshot.recentPain));
354
-
355
- // 4. Enqueue task (with lock acquisition)
356
- try {
357
- await enqueueSleepReflectionTask(taskId);
358
- logStep('STEP 3', `Enqueued sleep_reflection task: ${taskId}`);
359
-
360
- // Post-enqueue: verify queue state
361
- const queueAfter = safeReadJson(QUEUE_PATH) as QueueItem[] | null;
362
- const taskItem = queueAfter?.find(q => q.id === taskId);
363
- logData('EVOLUTION_QUEUE (after)', `${queueAfter?.length ?? 0} tasks`);
364
- logData(`task[${taskId}]`, taskItem ? JSON.stringify(taskItem) : 'NOT FOUND');
365
- } catch (error: unknown) {
366
- console.error('FAIL: Failed to enqueue sleep_reflection task:', String(error));
367
- process.exit(1);
368
- }
369
-
370
- // 5. Poll for completion — with data flow monitoring
371
- const deadline = Date.now() + POLL_TIMEOUT_MS;
372
- let pollCount = 0;
373
- let lastQueueStatus = 'unknown';
374
- let lastWorkflowState = 'none';
375
- logStep('STEP 4', `Polling for workflow completion (timeout: ${POLL_TIMEOUT_MS / 1000 / 60}min, interval: ${POLL_INTERVAL_MS / 1000}s)`);
376
-
377
- while (Date.now() < deadline) {
378
- pollCount++;
379
- await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
380
-
381
- // Capture queue state
382
- const queueNow = safeReadJson(QUEUE_PATH) as QueueItem[] | null;
383
- const taskNow = queueNow?.find(q => q.id === taskId);
384
- const currentQueueStatus = taskNow?.status ?? 'not_in_queue';
385
-
386
- // Capture workflow DB state
387
- const workflows = listNocturnalWorkflows();
388
- const matchingWf = workflows.find(w => {
389
- try {
390
- const meta = JSON.parse(w.metadata_json);
391
- return meta.taskId === taskId;
392
- } catch { return false; }
393
- });
394
- const currentWorkflowState = matchingWf?.state ?? 'not_in_db';
395
-
396
- // Log state changes
397
- if (currentQueueStatus !== lastQueueStatus || currentWorkflowState !== lastWorkflowState) {
398
- logStep(`POLL #${pollCount}`, `queue=${currentQueueStatus}, workflow=${currentWorkflowState}`);
399
- if (taskNow) logData('queue item', JSON.stringify({ status: taskNow.status, resolution: taskNow.resolution }));
400
- if (matchingWf) logData('workflow', JSON.stringify({ state: matchingWf.state, type: matchingWf.workflow_type }));
401
- lastQueueStatus = currentQueueStatus;
402
- lastWorkflowState = currentWorkflowState;
403
- } else if (verbose) {
404
- process.stdout.write('.');
405
- }
406
-
407
- // Check for completion
408
- const result = verifyWorkflowCompletion(taskId);
409
- if (result) {
410
- console.log(''); // newline if dots were printed
411
- logStep('STEP 5', `Workflow completed!`);
412
- logData('RESULT', `workflowId=${result.workflowId} state=${result.state} resolution=${result.resolution}`);
413
-
414
- // Check artifact persistence
415
- if (fs.existsSync(SAMPLES_DIR)) {
416
- const newSamples = fs.readdirSync(SAMPLES_DIR).filter(f => {
417
- const stat = fs.statSync(path.join(SAMPLES_DIR, f));
418
- return stat.isFile() && f.endsWith('.json') && (Date.now() - stat.mtimeMs) < 60000; // created in last minute
419
- });
420
- if (newSamples.length > 0) {
421
- logData('new artifacts', newSamples.join(', '));
422
- const firstArtifact = safeReadJson(path.join(SAMPLES_DIR, newSamples[0]));
423
- if (firstArtifact) logData('artifact content (first)', JSON.stringify(firstArtifact).slice(0, 300));
424
- } else {
425
- logData('new artifacts', 'none created in last 60s');
426
- }
427
- }
428
-
429
- if (result.resolution === 'MISSING' || result.resolution === 'expired') {
430
- console.error('FAIL: resolution not explicit');
431
- process.exit(1);
432
- }
433
-
434
- console.log('PASS: Live path validation successful');
435
- process.exit(0);
436
- }
437
- }
438
-
439
- // Timeout — dump final state for debugging
440
- console.log('');
441
- logStep('TIMEOUT', `Poll timeout after ${pollCount} polls (${POLL_TIMEOUT_MS / 1000 / 60}min)`);
442
- logData('FINAL queue status', lastQueueStatus);
443
- logData('FINAL workflow state', lastWorkflowState);
444
-
445
- // Dump full queue for debugging
446
- const finalQueue = safeReadJson(QUEUE_PATH);
447
- if (finalQueue) logData('FINAL queue dump', JSON.stringify(finalQueue).slice(0, 500));
448
-
449
- // Dump full workflow DB for debugging
450
- const finalWorkflows = listNocturnalWorkflows();
451
- if (finalWorkflows.length > 0) {
452
- logData('FINAL workflows', finalWorkflows.map(w => `${w.workflow_id}: state=${w.state}`).join(', '));
453
- }
454
-
455
- console.error('FAIL: No completed nocturnal workflow found for taskId');
456
- process.exit(1);
457
- }
458
-
459
- main().catch(err => {
460
- console.error('FAIL:', err);
461
- process.exit(1);
462
- });