principles-disciple 1.16.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +13 -5
  2. package/openclaw.plugin.json +4 -4
  3. package/package.json +1 -1
  4. package/src/commands/archive-impl.ts +3 -3
  5. package/src/commands/capabilities.ts +1 -1
  6. package/src/commands/context.ts +3 -3
  7. package/src/commands/disable-impl.ts +1 -1
  8. package/src/commands/evolution-status.ts +2 -2
  9. package/src/commands/focus.ts +2 -2
  10. package/src/commands/nocturnal-train.ts +6 -6
  11. package/src/commands/pain.ts +4 -4
  12. package/src/commands/pd-reflect.ts +87 -0
  13. package/src/commands/rollback-impl.ts +4 -4
  14. package/src/commands/rollback.ts +2 -2
  15. package/src/commands/samples.ts +2 -2
  16. package/src/commands/workflow-debug.ts +1 -1
  17. package/src/config/errors.ts +1 -1
  18. package/src/core/adaptive-thresholds.ts +1 -1
  19. package/src/core/code-implementation-storage.ts +2 -2
  20. package/src/core/config.ts +1 -1
  21. package/src/core/diagnostician-task-store.ts +2 -2
  22. package/src/core/empathy-keyword-matcher.ts +3 -3
  23. package/src/core/event-log.ts +5 -5
  24. package/src/core/evolution-engine.ts +4 -4
  25. package/src/core/evolution-logger.ts +1 -1
  26. package/src/core/evolution-reducer.ts +3 -3
  27. package/src/core/evolution-types.ts +5 -5
  28. package/src/core/external-training-contract.ts +1 -1
  29. package/src/core/focus-history.ts +14 -14
  30. package/src/core/hygiene/tracker.ts +1 -1
  31. package/src/core/init.ts +2 -2
  32. package/src/core/model-deployment-registry.ts +2 -2
  33. package/src/core/model-training-registry.ts +2 -2
  34. package/src/core/nocturnal-arbiter.ts +1 -1
  35. package/src/core/nocturnal-artificer.ts +2 -2
  36. package/src/core/nocturnal-candidate-scoring.ts +2 -2
  37. package/src/core/nocturnal-compliance.ts +4 -3
  38. package/src/core/nocturnal-dataset.ts +3 -3
  39. package/src/core/nocturnal-export.ts +4 -4
  40. package/src/core/nocturnal-rule-implementation-validator.ts +1 -1
  41. package/src/core/nocturnal-snapshot-contract.ts +112 -0
  42. package/src/core/nocturnal-trajectory-extractor.ts +7 -5
  43. package/src/core/nocturnal-trinity.ts +480 -158
  44. package/src/core/pain-context-extractor.ts +3 -3
  45. package/src/core/pain.ts +124 -11
  46. package/src/core/path-resolver.ts +4 -4
  47. package/src/core/pd-task-reconciler.ts +10 -10
  48. package/src/core/pd-task-service.ts +1 -1
  49. package/src/core/pd-task-store.ts +1 -1
  50. package/src/core/principle-internalization/deprecated-readiness.ts +1 -1
  51. package/src/core/principle-training-state.ts +2 -2
  52. package/src/core/principle-tree-ledger.ts +7 -7
  53. package/src/core/promotion-gate.ts +9 -9
  54. package/src/core/replay-engine.ts +12 -12
  55. package/src/core/risk-calculator.ts +1 -1
  56. package/src/core/rule-host-types.ts +2 -2
  57. package/src/core/rule-host.ts +5 -5
  58. package/src/core/schema/db-types.ts +1 -1
  59. package/src/core/schema/schema-definitions.ts +1 -1
  60. package/src/core/session-tracker.ts +96 -4
  61. package/src/core/shadow-observation-registry.ts +3 -3
  62. package/src/core/system-logger.ts +2 -2
  63. package/src/core/thinking-os-parser.ts +1 -1
  64. package/src/core/training-program.ts +2 -2
  65. package/src/core/trajectory.ts +8 -8
  66. package/src/core/workspace-context.ts +2 -2
  67. package/src/core/workspace-dir-service.ts +85 -0
  68. package/src/core/workspace-dir-validation.ts +30 -107
  69. package/src/hooks/bash-risk.ts +3 -3
  70. package/src/hooks/edit-verification.ts +4 -4
  71. package/src/hooks/gate-block-helper.ts +4 -4
  72. package/src/hooks/gate.ts +10 -10
  73. package/src/hooks/gfi-gate.ts +7 -7
  74. package/src/hooks/lifecycle.ts +2 -2
  75. package/src/hooks/llm.ts +1 -1
  76. package/src/hooks/pain.ts +25 -5
  77. package/src/hooks/progressive-trust-gate.ts +7 -7
  78. package/src/hooks/prompt.ts +24 -5
  79. package/src/hooks/subagent.ts +2 -2
  80. package/src/hooks/thinking-checkpoint.ts +2 -2
  81. package/src/hooks/trajectory-collector.ts +1 -1
  82. package/src/http/principles-console-route.ts +14 -6
  83. package/src/i18n/commands.ts +4 -0
  84. package/src/index.ts +181 -185
  85. package/src/service/central-health-service.ts +1 -1
  86. package/src/service/central-overview-service.ts +3 -3
  87. package/src/service/evolution-query-service.ts +1 -1
  88. package/src/service/evolution-worker.ts +221 -109
  89. package/src/service/health-query-service.ts +27 -17
  90. package/src/service/monitoring-query-service.ts +3 -3
  91. package/src/service/nocturnal-runtime.ts +4 -4
  92. package/src/service/nocturnal-service.ts +40 -23
  93. package/src/service/nocturnal-target-selector.ts +11 -4
  94. package/src/service/runtime-summary-service.ts +1 -1
  95. package/src/service/subagent-workflow/deep-reflect-workflow-manager.ts +1 -1
  96. package/src/service/subagent-workflow/empathy-observer-workflow-manager.ts +3 -3
  97. package/src/service/subagent-workflow/nocturnal-workflow-manager.ts +16 -13
  98. package/src/service/subagent-workflow/runtime-direct-driver.ts +10 -6
  99. package/src/service/subagent-workflow/types.ts +4 -4
  100. package/src/service/subagent-workflow/workflow-manager-base.ts +5 -5
  101. package/src/service/subagent-workflow/workflow-store.ts +2 -2
  102. package/src/tools/critique-prompt.ts +2 -3
  103. package/src/tools/deep-reflect.ts +17 -16
  104. package/src/tools/model-index.ts +1 -1
  105. package/src/utils/file-lock.ts +1 -1
  106. package/src/utils/io.ts +7 -2
  107. package/src/utils/nlp.ts +1 -1
  108. package/src/utils/plugin-logger.ts +2 -2
  109. package/src/utils/retry.ts +3 -2
  110. package/src/utils/subagent-probe.ts +20 -33
  111. package/templates/langs/en/skills/pd-pain-signal/SKILL.md +8 -7
  112. package/templates/langs/zh/skills/ai-sprint-orchestration/references/specs/nocturnal-trinity-quality-enhancement.json +111 -0
  113. package/templates/langs/zh/skills/ai-sprint-orchestration/scripts/lib/task-specs.mjs +1 -1
  114. package/templates/langs/zh/skills/ai-sprint-orchestration/scripts/run.mjs +1 -1
  115. package/templates/langs/zh/skills/pd-pain-signal/SKILL.md +8 -7
  116. package/templates/pain_settings.json +1 -1
  117. package/tests/build-artifacts.test.ts +4 -58
  118. package/tests/commands/pd-reflect.test.ts +49 -0
  119. package/tests/core/nocturnal-snapshot-contract.test.ts +70 -0
  120. package/tests/core/pain-auto-repair.test.ts +96 -0
  121. package/tests/core/pain-integration.test.ts +483 -0
  122. package/tests/core/pain.test.ts +5 -4
  123. package/tests/core/workspace-dir-service.test.ts +68 -0
  124. package/tests/core/workspace-dir-validation.test.ts +56 -192
  125. package/tests/hooks/pain.test.ts +20 -0
  126. package/tests/http/principles-console-route.test.ts +42 -20
  127. package/tests/integration/empathy-workflow-integration.test.ts +1 -2
  128. package/tests/integration/tool-hooks-workspace-dir.e2e.test.ts +9 -17
  129. package/tests/service/empathy-observer-workflow-manager.test.ts +1 -2
  130. package/tests/service/evolution-worker.nocturnal.test.ts +118 -109
  131. package/tests/service/nocturnal-runtime-hardening.test.ts +33 -0
  132. package/tests/utils/subagent-probe.test.ts +32 -0
@@ -0,0 +1,49 @@
1
+ import { beforeEach, describe, expect, it } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import { handlePdReflect } from '../../src/commands/pd-reflect.js';
6
+
7
+ describe('pd-reflect command', () => {
8
+ let tempDir: string;
9
+ let workspaceDir: string;
10
+ let queuePath: string;
11
+
12
+ beforeEach(() => {
13
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-reflect-'));
14
+ workspaceDir = path.join(tempDir, 'workspace-a');
15
+ fs.mkdirSync(path.join(workspaceDir, '.state'), { recursive: true });
16
+ queuePath = path.join(workspaceDir, '.state', 'evolution_queue.json');
17
+ fs.writeFileSync(queuePath, '[]', 'utf8');
18
+ });
19
+
20
+ it('requires an explicit resolved workspace directory', async () => {
21
+ const result = await handlePdReflect.handler({} as any);
22
+ expect(result.isError).toBe(true);
23
+ expect(result.text).toContain('Cannot determine workspace directory');
24
+ });
25
+
26
+ it('enqueues into the provided active workspace', async () => {
27
+ const result = await handlePdReflect.handler({ workspaceDir } as any);
28
+ expect(result.isError).toBeUndefined();
29
+
30
+ const queue = JSON.parse(fs.readFileSync(queuePath, 'utf8')) as Array<Record<string, unknown>>;
31
+ expect(queue).toHaveLength(1);
32
+ expect(queue[0].taskKind).toBe('sleep_reflection');
33
+ expect(result.text).toContain('Nocturnal reflection task enqueued');
34
+ });
35
+
36
+ it('does not hardcode another workspace when context already provides one', async () => {
37
+ const otherWorkspace = path.join(tempDir, 'workspace-b');
38
+ fs.mkdirSync(path.join(otherWorkspace, '.state'), { recursive: true });
39
+ const otherQueuePath = path.join(otherWorkspace, '.state', 'evolution_queue.json');
40
+ fs.writeFileSync(otherQueuePath, '[]', 'utf8');
41
+
42
+ await handlePdReflect.handler({ workspaceDir } as any);
43
+
44
+ const activeQueue = JSON.parse(fs.readFileSync(queuePath, 'utf8')) as Array<Record<string, unknown>>;
45
+ const otherQueue = JSON.parse(fs.readFileSync(otherQueuePath, 'utf8')) as Array<Record<string, unknown>>;
46
+ expect(activeQueue).toHaveLength(1);
47
+ expect(otherQueue).toHaveLength(0);
48
+ });
49
+ });
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { validateNocturnalSnapshotIngress } from '../../src/core/nocturnal-snapshot-contract.js';
3
+
4
+ describe('validateNocturnalSnapshotIngress', () => {
5
+ it('accepts a fully shaped runtime snapshot', () => {
6
+ const result = validateNocturnalSnapshotIngress({
7
+ sessionId: 'session-1',
8
+ startedAt: '2026-04-10T00:00:00.000Z',
9
+ updatedAt: '2026-04-10T00:01:00.000Z',
10
+ assistantTurns: [],
11
+ userTurns: [],
12
+ toolCalls: [],
13
+ painEvents: [],
14
+ gateBlocks: [],
15
+ stats: {
16
+ totalAssistantTurns: 1,
17
+ totalToolCalls: 2,
18
+ totalPainEvents: 0,
19
+ totalGateBlocks: 0,
20
+ failureCount: 0,
21
+ },
22
+ });
23
+
24
+ expect(result.status).toBe('valid');
25
+ expect(result.snapshot?.sessionId).toBe('session-1');
26
+ });
27
+
28
+ it('rejects reduced pseudo-snapshots that omit canonical fields', () => {
29
+ const result = validateNocturnalSnapshotIngress({
30
+ sessionId: 'session-1',
31
+ sessionStart: '2026-04-10T00:00:00.000Z',
32
+ stats: {
33
+ totalAssistantTurns: 1,
34
+ totalToolCalls: 2,
35
+ totalPainEvents: 0,
36
+ totalGateBlocks: 0,
37
+ failureCount: 0,
38
+ },
39
+ recentPain: [],
40
+ });
41
+
42
+ expect(result.status).toBe('invalid');
43
+ expect(result.reasons).toContain('snapshot.startedAt must be a non-empty string');
44
+ expect(result.reasons).toContain('snapshot.assistantTurns must be an array');
45
+ });
46
+
47
+ it('rejects fallback snapshots with no pain signal', () => {
48
+ const result = validateNocturnalSnapshotIngress({
49
+ sessionId: 'session-1',
50
+ startedAt: '2026-04-10T00:00:00.000Z',
51
+ updatedAt: '2026-04-10T00:00:00.000Z',
52
+ assistantTurns: [],
53
+ userTurns: [],
54
+ toolCalls: [],
55
+ painEvents: [],
56
+ gateBlocks: [],
57
+ stats: {
58
+ totalAssistantTurns: null,
59
+ totalToolCalls: null,
60
+ totalPainEvents: 0,
61
+ totalGateBlocks: null,
62
+ failureCount: null,
63
+ },
64
+ _dataSource: 'pain_context_fallback',
65
+ });
66
+
67
+ expect(result.status).toBe('invalid');
68
+ expect(result.reasons).toContain('fallback snapshot must contain at least one pain signal');
69
+ });
70
+ });
@@ -0,0 +1,96 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import { readPainFlagData, readPainFlagContract, buildPainFlag, writePainFlag } from '../../src/core/pain.js';
6
+
7
+ const TEST_DIR = path.join(os.tmpdir(), 'test-pain-auto-repair');
8
+
9
+ describe('Pain Flag Auto-Repair', () => {
10
+ beforeEach(() => {
11
+ fs.mkdirSync(path.join(TEST_DIR, '.state'), { recursive: true });
12
+ });
13
+
14
+ afterEach(() => {
15
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
16
+ });
17
+
18
+ it('should auto-repair JSON format pain flag to KV format', () => {
19
+ const jsonContent = JSON.stringify({
20
+ severity: 'HIGH',
21
+ source: 'team-audit',
22
+ reason: 'test auto-repair from JSON',
23
+ timestamp: '2026-03-19T08:37:00Z',
24
+ confidence: 0.95,
25
+ });
26
+ fs.writeFileSync(path.join(TEST_DIR, '.state/.pain_flag'), jsonContent, 'utf-8');
27
+
28
+ const result = readPainFlagData(TEST_DIR);
29
+
30
+ // Should have parsed and mapped fields
31
+ expect(result.source).toBe('team-audit');
32
+ expect(result.reason).toBe('test auto-repair from JSON');
33
+ expect(result.time).toBe('2026-03-19T08:37:00Z');
34
+ expect(result.severity).toBe('HIGH');
35
+
36
+ // File should have been rewritten in KV format
37
+ const repaired = fs.readFileSync(path.join(TEST_DIR, '.state/.pain_flag'), 'utf-8');
38
+ expect(repaired).not.toContain('{');
39
+ expect(repaired).toContain('source: team-audit');
40
+ expect(repaired).toContain('time: 2026-03-19T08:37:00Z');
41
+ });
42
+
43
+ it('should parse valid KV format without modification', () => {
44
+ const kvContent = `is_risky: false
45
+ reason: test reason
46
+ score: 50
47
+ source: tool_failure
48
+ time: 2026-03-20T02:19:47.445Z`;
49
+ fs.writeFileSync(path.join(TEST_DIR, '.state/.pain_flag'), kvContent, 'utf-8');
50
+
51
+ const result = readPainFlagData(TEST_DIR);
52
+
53
+ expect(result.source).toBe('tool_failure');
54
+ expect(result.score).toBe('50');
55
+ expect(result.reason).toBe('test reason');
56
+
57
+ // File should be unchanged
58
+ const after = fs.readFileSync(path.join(TEST_DIR, '.state/.pain_flag'), 'utf-8');
59
+ expect(after).toBe(kvContent);
60
+ });
61
+
62
+ it('should return empty object for missing file', () => {
63
+ const result = readPainFlagData(TEST_DIR);
64
+ expect(result).toEqual({});
65
+ });
66
+
67
+ it('should return empty object for empty file', () => {
68
+ fs.writeFileSync(path.join(TEST_DIR, '.state/.pain_flag'), '', 'utf-8');
69
+ const result = readPainFlagData(TEST_DIR);
70
+ expect(result).toEqual({});
71
+ });
72
+
73
+ it('should warn on missing required fields in KV format', () => {
74
+ const kvContent = `score: 50
75
+ source: tool_failure`;
76
+ fs.writeFileSync(path.join(TEST_DIR, '.state/.pain_flag'), kvContent, 'utf-8');
77
+
78
+ const result = readPainFlagData(TEST_DIR);
79
+
80
+ // Should still parse the available fields
81
+ expect(result.source).toBe('tool_failure');
82
+ expect(result.score).toBe('50');
83
+ // Missing time and reason — validation will log a warning
84
+ });
85
+ it('returns invalid contract result for missing required fields', () => {
86
+ const kvContent = `score: 50
87
+ source: tool_failure`;
88
+ fs.writeFileSync(path.join(TEST_DIR, '.state/.pain_flag'), kvContent, 'utf-8');
89
+
90
+ const contract = readPainFlagContract(TEST_DIR);
91
+
92
+ expect(contract.status).toBe('invalid');
93
+ expect(contract.format).toBe('kv');
94
+ expect(contract.missingFields).toEqual(expect.arrayContaining(['time', 'reason']));
95
+ });
96
+ });
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Pain Flag Integration Tests
3
+ *
4
+ * These tests use the REAL file system to verify end-to-end behavior:
5
+ * - writePainFlag writes correct KV format
6
+ * - readPainFlagData reads back correctly
7
+ * - Auto-repair from JSON to KV works
8
+ * - Empty/undefined values are NOT written to disk
9
+ * - Round-trip: write → read → verify
10
+ */
11
+
12
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
13
+ import * as fs from 'fs';
14
+ import * as os from 'os';
15
+ import * as path from 'path';
16
+ import {
17
+ buildPainFlag,
18
+ writePainFlag,
19
+ readPainFlagData,
20
+ validatePainFlag,
21
+ } from '../../src/core/pain.js';
22
+
23
+ const TEST_DIR = path.join(os.tmpdir(), 'test-pain-integration');
24
+ const STATE_DIR = path.join(TEST_DIR, '.state');
25
+
26
+ describe('Pain Flag Integration (real FS)', () => {
27
+ beforeEach(() => {
28
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
29
+ fs.mkdirSync(STATE_DIR, { recursive: true });
30
+ });
31
+
32
+ afterEach(() => {
33
+ fs.rmSync(TEST_DIR, { recursive: true, force: true });
34
+ });
35
+
36
+ // ── Round-trip tests ──────────────────────────────────────────────
37
+
38
+ describe('Round-trip: write → read', () => {
39
+ it('should write and read back a complete pain flag', () => {
40
+ const data = buildPainFlag({
41
+ source: 'tool_failure',
42
+ score: '50',
43
+ reason: 'Test failure reason',
44
+ session_id: 'test-session-123',
45
+ agent_id: 'main',
46
+ is_risky: false,
47
+ });
48
+
49
+ writePainFlag(TEST_DIR, data);
50
+
51
+ const read = readPainFlagData(TEST_DIR);
52
+
53
+ expect(read.source).toBe('tool_failure');
54
+ expect(read.score).toBe('50');
55
+ expect(read.reason).toBe('Test failure reason');
56
+ expect(read.session_id).toBe('test-session-123');
57
+ expect(read.agent_id).toBe('main');
58
+ expect(read.is_risky).toBe('false');
59
+ expect(read.time).toBeDefined();
60
+ });
61
+
62
+ it('should NOT write empty optional fields to disk', () => {
63
+ const data = buildPainFlag({
64
+ source: 'human_intervention',
65
+ score: '80',
66
+ reason: 'User feedback',
67
+ // session_id, agent_id, trace_id, trigger_text_preview all omitted
68
+ });
69
+
70
+ writePainFlag(TEST_DIR, data);
71
+
72
+ const fileContent = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
73
+
74
+ // Empty fields should not appear in the file
75
+ expect(fileContent).not.toContain('trace_id');
76
+ expect(fileContent).not.toContain('trigger_text_preview');
77
+ // session_id/agent_id are empty strings so should be skipped too
78
+ expect(fileContent).not.toContain('session_id:');
79
+ expect(fileContent).not.toContain('agent_id:');
80
+
81
+ // But required fields must be present
82
+ expect(fileContent).toContain('source: human_intervention');
83
+ expect(fileContent).toContain('score: 80');
84
+ expect(fileContent).toContain('reason: User feedback');
85
+ });
86
+
87
+ it('should write non-empty optional fields', () => {
88
+ const data = buildPainFlag({
89
+ source: 'tool_failure',
90
+ score: '70',
91
+ reason: 'Edit failed',
92
+ session_id: 'boot-abc123',
93
+ agent_id: 'builder',
94
+ trace_id: 'ev_test_trace_001',
95
+ trigger_text_preview: 'short preview text',
96
+ });
97
+
98
+ writePainFlag(TEST_DIR, data);
99
+
100
+ const fileContent = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
101
+
102
+ expect(fileContent).toContain('session_id: boot-abc123');
103
+ expect(fileContent).toContain('agent_id: builder');
104
+ expect(fileContent).toContain('trace_id: ev_test_trace_001');
105
+ expect(fileContent).toContain('trigger_text_preview: short preview text');
106
+ });
107
+
108
+ it('should handle risky flag correctly', () => {
109
+ const data = buildPainFlag({
110
+ source: 'intercept_extraction',
111
+ score: '100',
112
+ reason: 'Hard intercept',
113
+ is_risky: true,
114
+ });
115
+
116
+ writePainFlag(TEST_DIR, data);
117
+
118
+ const read = readPainFlagData(TEST_DIR);
119
+ expect(read.is_risky).toBe('true');
120
+ });
121
+ });
122
+
123
+ // ── File format validation ────────────────────────────────────────
124
+
125
+ describe('File format', () => {
126
+ it('should write KV format (not JSON)', () => {
127
+ const data = buildPainFlag({
128
+ source: 'tool_failure',
129
+ score: '50',
130
+ reason: 'test',
131
+ });
132
+
133
+ writePainFlag(TEST_DIR, data);
134
+
135
+ const fileContent = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
136
+
137
+ // Should NOT be JSON
138
+ expect(fileContent).not.toContain('{');
139
+ expect(fileContent).not.toContain('}');
140
+ // Should be KV format with colon separator
141
+ expect(fileContent).toContain('source: tool_failure');
142
+ expect(fileContent).toContain('score: 50');
143
+ });
144
+
145
+ it('should have fields sorted alphabetically', () => {
146
+ const data = buildPainFlag({
147
+ source: 'tool_failure',
148
+ score: '50',
149
+ reason: 'test',
150
+ session_id: 'sess1',
151
+ agent_id: 'main',
152
+ trace_id: 'trace1',
153
+ });
154
+
155
+ writePainFlag(TEST_DIR, data);
156
+
157
+ const fileContent = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
158
+ const lines = fileContent.trim().split('\n');
159
+ const keys = lines.map(l => l.split(':')[0].trim());
160
+
161
+ // Keys should be in alphabetical order (serializeKvLines sorts)
162
+ expect(keys).toEqual([...keys].sort());
163
+ });
164
+
165
+ it('should not have blank lines in output', () => {
166
+ const data = buildPainFlag({
167
+ source: 'tool_failure',
168
+ score: '50',
169
+ reason: 'test',
170
+ });
171
+
172
+ writePainFlag(TEST_DIR, data);
173
+
174
+ const fileContent = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
175
+ const lines = fileContent.split('\n');
176
+
177
+ // No empty lines
178
+ for (const line of lines) {
179
+ expect(line.trim()).not.toBe('');
180
+ }
181
+ });
182
+ });
183
+
184
+ // ── Auto-repair tests ─────────────────────────────────────────────
185
+
186
+ describe('Auto-repair from wrong formats', () => {
187
+ it('should repair JSON format to KV format', () => {
188
+ const jsonContent = JSON.stringify({
189
+ source: 'team-audit',
190
+ score: '60',
191
+ reason: 'zero output loop',
192
+ timestamp: '2026-03-19T08:37:00Z',
193
+ severity: 'HIGH',
194
+ });
195
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), jsonContent, 'utf-8');
196
+
197
+ const result = readPainFlagData(TEST_DIR);
198
+
199
+ // Should parse correctly
200
+ expect(result.source).toBe('team-audit');
201
+ expect(result.score).toBe('60');
202
+ expect(result.reason).toBe('zero output loop');
203
+ expect(result.time).toBe('2026-03-19T08:37:00Z');
204
+
205
+ // File should be rewritten in KV format
206
+ const repaired = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
207
+ expect(repaired).not.toContain('{');
208
+ expect(repaired).toContain('source: team-audit');
209
+ });
210
+
211
+ it('should repair JSON with camelCase field names', () => {
212
+ const jsonContent = JSON.stringify({
213
+ source: 'llm_detection',
214
+ score: '45',
215
+ reason: 'spiral detected',
216
+ sessionId: 'sess-camel',
217
+ agentId: 'main',
218
+ isRisky: false,
219
+ });
220
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), jsonContent, 'utf-8');
221
+
222
+ const result = readPainFlagData(TEST_DIR);
223
+
224
+ expect(result.source).toBe('llm_detection');
225
+ expect(result.session_id).toBe('sess-camel');
226
+ expect(result.agent_id).toBe('main');
227
+ expect(result.is_risky).toBe('false');
228
+ });
229
+
230
+ it('should handle corrupted JSON gracefully', () => {
231
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), '{bad json}', 'utf-8');
232
+
233
+ const result = readPainFlagData(TEST_DIR);
234
+ expect(result).toEqual({});
235
+ });
236
+
237
+ it('should handle partially malformed KV format', () => {
238
+ // Missing colons on some lines
239
+ const content = `source: tool_failure
240
+ score: 50
241
+ reason missing colon
242
+ time: 2026-03-20T02:19:47.445Z`;
243
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), content, 'utf-8');
244
+
245
+ const result = readPainFlagData(TEST_DIR);
246
+
247
+ // Should parse lines that have colons, skip ones that don't
248
+ expect(result.source).toBe('tool_failure');
249
+ expect(result.score).toBe('50');
250
+ expect(result.time).toBe('2026-03-20T02:19:47.445Z');
251
+ });
252
+
253
+ it('should handle empty file', () => {
254
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), '', 'utf-8');
255
+
256
+ const result = readPainFlagData(TEST_DIR);
257
+ expect(result).toEqual({});
258
+ });
259
+
260
+ it('should handle whitespace-only file', () => {
261
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), ' \n\n \n', 'utf-8');
262
+
263
+ const result = readPainFlagData(TEST_DIR);
264
+ expect(result).toEqual({});
265
+ });
266
+ });
267
+
268
+ // ── Edge cases ────────────────────────────────────────────────────
269
+
270
+ describe('Edge cases', () => {
271
+ it('should handle special characters in reason', () => {
272
+ const data = buildPainFlag({
273
+ source: 'tool_failure',
274
+ score: '50',
275
+ reason: 'Edit failed: "old text" not found in file.ts — expected: "foo", got: "bar"',
276
+ });
277
+
278
+ writePainFlag(TEST_DIR, data);
279
+ const read = readPainFlagData(TEST_DIR);
280
+
281
+ expect(read.reason).toContain('"old text"');
282
+ expect(read.reason).toContain('expected: "foo"');
283
+ expect(read.reason).toContain('got: "bar"');
284
+ });
285
+
286
+ it('should handle multiline reason by preserving only first line (KV limitation)', () => {
287
+ // KV format is line-based — newlines in values will be split across lines
288
+ // This is a known limitation; reasons should be single-line
289
+ const multilineReason = 'Line one\nLine two';
290
+ const data = buildPainFlag({
291
+ source: 'tool_failure',
292
+ score: '50',
293
+ reason: multilineReason,
294
+ });
295
+
296
+ writePainFlag(TEST_DIR, data);
297
+ const read = readPainFlagData(TEST_DIR);
298
+
299
+ // Only first line is preserved (KV line-based format)
300
+ expect(read.reason).toBe('Line one');
301
+ });
302
+
303
+ it('should handle Chinese characters in reason', () => {
304
+ const data = buildPainFlag({
305
+ source: 'human_intervention',
306
+ score: '80',
307
+ reason: '用户报告agent卡住,反复循环',
308
+ });
309
+
310
+ writePainFlag(TEST_DIR, data);
311
+ const read = readPainFlagData(TEST_DIR);
312
+
313
+ expect(read.reason).toBe('用户报告agent卡住,反复循环');
314
+ });
315
+
316
+ it('should handle very long reason strings', () => {
317
+ const longReason = 'x'.repeat(5000);
318
+ const data = buildPainFlag({
319
+ source: 'tool_failure',
320
+ score: '50',
321
+ reason: longReason,
322
+ });
323
+
324
+ writePainFlag(TEST_DIR, data);
325
+ const read = readPainFlagData(TEST_DIR);
326
+
327
+ expect(read.reason).toBe(longReason);
328
+ });
329
+
330
+ it('should handle source values with underscores', () => {
331
+ const sources = [
332
+ 'tool_failure',
333
+ 'human_intervention',
334
+ 'intercept_extraction',
335
+ 'subagent_error',
336
+ 'subagent_timeout',
337
+ 'compaction_pain',
338
+ 'main_self_observation',
339
+ ];
340
+
341
+ for (const src of sources) {
342
+ const data = buildPainFlag({
343
+ source: src,
344
+ score: '50',
345
+ reason: 'test',
346
+ });
347
+
348
+ writePainFlag(TEST_DIR, data);
349
+ const read = readPainFlagData(TEST_DIR);
350
+
351
+ expect(read.source, `source "${src}" should round-trip`).toBe(src);
352
+ }
353
+ });
354
+
355
+ it('should handle score edge cases (0 and 100)', () => {
356
+ const data = buildPainFlag({
357
+ source: 'test',
358
+ score: '0',
359
+ reason: 'minimum score',
360
+ });
361
+
362
+ writePainFlag(TEST_DIR, data);
363
+ const read = readPainFlagData(TEST_DIR);
364
+
365
+ expect(read.score).toBe('0');
366
+ });
367
+
368
+ it('should overwrite existing file (not append)', () => {
369
+ // Write first flag
370
+ const data1 = buildPainFlag({
371
+ source: 'first_signal',
372
+ score: '30',
373
+ reason: 'first',
374
+ });
375
+ writePainFlag(TEST_DIR, data1);
376
+
377
+ // Write second flag
378
+ const data2 = buildPainFlag({
379
+ source: 'second_signal',
380
+ score: '60',
381
+ reason: 'second',
382
+ });
383
+ writePainFlag(TEST_DIR, data2);
384
+
385
+ // Should only have second
386
+ const read = readPainFlagData(TEST_DIR);
387
+ expect(read.source).toBe('second_signal');
388
+ expect(read.score).toBe('60');
389
+
390
+ // File should not contain first
391
+ const content = fs.readFileSync(path.join(STATE_DIR, '.pain_flag'), 'utf-8');
392
+ expect(content).not.toContain('first_signal');
393
+ });
394
+ });
395
+
396
+ // ── Validation on read ────────────────────────────────────────────
397
+
398
+ describe('Validation on read', () => {
399
+ it('should read KV with all fields', () => {
400
+ const content = `agent_id: main
401
+ is_risky: false
402
+ reason: complete test
403
+ score: 70
404
+ session_id: sess-123
405
+ source: tool_failure
406
+ time: 2026-04-10T09:00:00.000Z`;
407
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), content, 'utf-8');
408
+
409
+ const result = readPainFlagData(TEST_DIR);
410
+
411
+ expect(result).toEqual({
412
+ agent_id: 'main',
413
+ is_risky: 'false',
414
+ reason: 'complete test',
415
+ score: '70',
416
+ session_id: 'sess-123',
417
+ source: 'tool_failure',
418
+ time: '2026-04-10T09:00:00.000Z',
419
+ });
420
+
421
+ const missing = validatePainFlag(result);
422
+ expect(missing).toEqual([]);
423
+ });
424
+
425
+ it('should read KV with only required fields', () => {
426
+ const content = `reason: minimal test
427
+ score: 40
428
+ source: human_intervention
429
+ time: 2026-04-10T09:00:00.000Z`;
430
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), content, 'utf-8');
431
+
432
+ const result = readPainFlagData(TEST_DIR);
433
+
434
+ expect(result.source).toBe('human_intervention');
435
+ expect(result.score).toBe('40');
436
+ expect(result.reason).toBe('minimal test');
437
+ expect(result.time).toBe('2026-04-10T09:00:00.000Z');
438
+
439
+ const missing = validatePainFlag(result);
440
+ expect(missing).toEqual([]);
441
+ });
442
+
443
+ it('should read KV with extra unknown fields', () => {
444
+ const content = `custom_field: custom_value
445
+ reason: extra fields test
446
+ score: 50
447
+ source: tool_failure
448
+ time: 2026-04-10T09:00:00.000Z
449
+ unknown_meta: some data`;
450
+ fs.writeFileSync(path.join(STATE_DIR, '.pain_flag'), content, 'utf-8');
451
+
452
+ const result = readPainFlagData(TEST_DIR);
453
+
454
+ // Unknown fields should be preserved
455
+ expect(result.custom_field).toBe('custom_value');
456
+ expect(result.unknown_meta).toBe('some data');
457
+ // Required fields should still work
458
+ expect(result.source).toBe('tool_failure');
459
+ });
460
+ });
461
+
462
+ // ── Missing file scenarios ────────────────────────────────────────
463
+
464
+ describe('Missing file scenarios', () => {
465
+ it('should return empty object when .pain_flag does not exist', () => {
466
+ // Don't create the file
467
+ const result = readPainFlagData(TEST_DIR);
468
+ expect(result).toEqual({});
469
+ });
470
+
471
+ it('should return empty object when .state directory does not exist', () => {
472
+ const freshDir = '/tmp/test-pain-no-state';
473
+ fs.rmSync(freshDir, { recursive: true, force: true });
474
+
475
+ try {
476
+ const result = readPainFlagData(freshDir);
477
+ expect(result).toEqual({});
478
+ } finally {
479
+ fs.rmSync(freshDir, { recursive: true, force: true });
480
+ }
481
+ });
482
+ });
483
+ });