@sanqianx/project-knowledge 4.6.1 → 4.8.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 (198) hide show
  1. package/.agents/plugins/marketplace.json +17 -17
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/CHANGELOG.md +817 -780
  4. package/README.md +48 -36
  5. package/_modules/knowledge-engine/README.md +88 -0
  6. package/_modules/knowledge-engine/package.json +38 -0
  7. package/_modules/knowledge-engine/src/analysis-contract.js +25 -0
  8. package/_modules/knowledge-engine/src/analysis-worker.js +54 -0
  9. package/_modules/knowledge-engine/src/bin.js +52 -0
  10. package/_modules/knowledge-engine/src/bridge-client.js +24 -0
  11. package/_modules/knowledge-engine/src/coordinator.js +255 -0
  12. package/_modules/knowledge-engine/src/headless-analyzer.js +75 -0
  13. package/_modules/knowledge-engine/src/memories.js +85 -0
  14. package/_modules/knowledge-engine/src/migration.js +88 -0
  15. package/_modules/knowledge-engine/src/retrieval.js +116 -0
  16. package/_modules/knowledge-engine/src/runtime/README.md +7 -0
  17. package/_modules/knowledge-engine/src/runtime/atomic-file.js +204 -0
  18. package/_modules/knowledge-engine/src/runtime/automation-config.js +140 -0
  19. package/_modules/knowledge-engine/src/runtime/commit-conversation-binder.js +249 -0
  20. package/_modules/knowledge-engine/src/runtime/commit-processing-ledger.js +26 -0
  21. package/_modules/knowledge-engine/src/runtime/commit-prompt.js +202 -0
  22. package/_modules/knowledge-engine/src/runtime/commit-reconciler.js +432 -0
  23. package/_modules/knowledge-engine/src/runtime/content-hash.js +4 -0
  24. package/_modules/knowledge-engine/src/runtime/contracts.js +279 -0
  25. package/_modules/knowledge-engine/src/runtime/conversation-exclusions.js +204 -0
  26. package/_modules/knowledge-engine/src/runtime/conversation-store.js +387 -0
  27. package/_modules/knowledge-engine/src/runtime/evidence-bundle.js +228 -0
  28. package/_modules/knowledge-engine/src/runtime/git-runner.js +62 -0
  29. package/_modules/knowledge-engine/src/runtime/knowledge-promotion.js +444 -0
  30. package/_modules/knowledge-engine/src/runtime/knowledge-retrieval-service.js +402 -0
  31. package/_modules/knowledge-engine/src/runtime/layout.js +44 -0
  32. package/_modules/knowledge-engine/src/runtime/markdown-knowledge-indexer.js +230 -0
  33. package/_modules/knowledge-engine/src/runtime/scanner.js +298 -0
  34. package/_modules/knowledge-engine/src/server.js +155 -0
  35. package/_modules/knowledge-engine/src/store.js +239 -0
  36. package/_modules/knowledge-engine/ui/app.css +172 -0
  37. package/_modules/knowledge-engine/ui/app.js +297 -0
  38. package/_modules/knowledge-engine/ui/index.html +95 -0
  39. package/_site/README.md +30 -30
  40. package/_site/_test/ai-profile-resolver-test.js +137 -137
  41. package/_site/_test/automation-queue-test.js +14 -14
  42. package/_site/_test/automation-ui-test.js +40 -40
  43. package/_site/_test/background-task-registry-test.js +43 -43
  44. package/_site/_test/baseline-schema-test.js +91 -91
  45. package/_site/_test/bridge-adapter-test.js +1 -1
  46. package/_site/_test/bridge-consumer-service-test.js +1 -1
  47. package/_site/_test/chat-claudecodeui-match-test.js +92 -92
  48. package/_site/_test/claude-executable-discovery-test.js +62 -62
  49. package/_site/_test/claude-workbench-test.js +170 -170
  50. package/_site/_test/client-capture-restart-e2e-test.js +4 -4
  51. package/_site/_test/codex-conversation-projection-test.js +2 -1
  52. package/_site/_test/commit-boundary-freeze-test.js +1 -1
  53. package/_site/_test/commit-conversation-binding-test.js +95 -95
  54. package/_site/_test/commit-evidence-test.js +110 -110
  55. package/_site/_test/conversation-api-test.js +109 -109
  56. package/_site/_test/conversation-store-test.js +136 -136
  57. package/_site/_test/cross-repo-isolation-e2e-test.js +2 -2
  58. package/_site/_test/data-dir-migration-test.js +57 -57
  59. package/_site/_test/desktop-browser-compat-test.js +28 -28
  60. package/_site/_test/desktop-hook-runtime-regression-test.js +204 -204
  61. package/_site/_test/explicit-commit-processor-test.js +37 -37
  62. package/_site/_test/fixtures/make-git-repos.js +12 -1
  63. package/_site/_test/folder-picker-output-test.js +19 -19
  64. package/_site/_test/full-integration-e2e-test.js +165 -165
  65. package/_site/_test/git-validation-test.js +2 -2
  66. package/_site/_test/hook-runtime-endpoint-test.js +88 -88
  67. package/_site/_test/hook-status-repair-api-test.js +152 -152
  68. package/_site/_test/hook-trigger-test.js +85 -85
  69. package/_site/_test/import-preflight-api-test.js +234 -233
  70. package/_site/_test/index-writer-concurrency-test.js +135 -135
  71. package/_site/_test/integration-adapters-test.js +171 -171
  72. package/_site/_test/integration-capture-setup-test.js +1 -1
  73. package/_site/_test/integration-surface-coverage-test.js +164 -164
  74. package/_site/_test/knowledge-language-control-test.js +170 -170
  75. package/_site/_test/knowledge-promotion-recovery-test.js +260 -260
  76. package/_site/_test/knowledge-query-test.js +54 -54
  77. package/_site/_test/knowledge-retrieval-service-test.js +77 -77
  78. package/_site/_test/knowledge-storage-startup-test.js +52 -52
  79. package/_site/_test/knowledge-store-logs-supervision-test.js +89 -89
  80. package/_site/_test/legacy-forward-compat-test.js +257 -257
  81. package/_site/_test/legacy-project-upgrade-e2e-test.js +363 -363
  82. package/_site/_test/logging-api-test.js +89 -89
  83. package/_site/_test/logging-sse-no-gap-test.js +88 -88
  84. package/_site/_test/logging-ui-test.js +106 -104
  85. package/_site/_test/markdown-delta-overlay-test.js +85 -85
  86. package/_site/_test/markdown-maintenance-api-test.js +75 -75
  87. package/_site/_test/mcp-server-test.js +149 -149
  88. package/_site/_test/module-artifact-integrity-test.js +27 -0
  89. package/_site/_test/module-boundary-test.js +30 -0
  90. package/_site/_test/module-bridge-eventbridge-test.js +7 -0
  91. package/_site/_test/module-model-configuration-test.js +43 -0
  92. package/_site/_test/module-process-lifecycle-test.js +24 -0
  93. package/_site/_test/module-stream-proxy-test.js +34 -0
  94. package/_site/_test/non-release-ci-test.js +34 -34
  95. package/_site/_test/offline-boundary-isolation-test.js +32 -32
  96. package/_site/_test/p0-data-migration-characterization-test.js +37 -37
  97. package/_site/_test/p0-e2e-gate-test.js +347 -347
  98. package/_site/_test/packaged-ui-smoke-test.js +19 -10
  99. package/_site/_test/path-consistency-test.js +151 -151
  100. package/_site/_test/pending-sweep-test.js +9 -9
  101. package/_site/_test/post-commit-automation-test.js +87 -87
  102. package/_site/_test/product-diagnostics-ui-test.js +75 -0
  103. package/_site/_test/product-import-ui-test.js +92 -0
  104. package/_site/_test/project-delete-recovery-test.js +64 -64
  105. package/_site/_test/project-goal-editor-test.js +144 -144
  106. package/_site/_test/project-layout-v2-migration-test.js +127 -127
  107. package/_site/_test/project-lifecycle-transaction-test.js +106 -106
  108. package/_site/_test/prompt-settings-test.js +115 -115
  109. package/_site/_test/protected-architecture-gate-test.js +122 -122
  110. package/_site/_test/refactor-characterization-test.js +36 -36
  111. package/_site/_test/release-version-sync-test.js +1 -1
  112. package/_site/_test/requirement-recorder-test.js +173 -173
  113. package/_site/_test/run-all-tests.js +159 -156
  114. package/_site/_test/server-runtime-migration-safety-test.js +27 -27
  115. package/_site/_test/shared-contracts-test.js +58 -58
  116. package/_site/_test/startup-analysis-disabled-test.js +10 -10
  117. package/_site/_test/storage-foundation-test.js +78 -78
  118. package/_site/_test/structured-logger-test.js +101 -101
  119. package/_site/_test/tracking-start-test.js +108 -108
  120. package/_site/_test/v4122-upgrade-data-contract-test.js +56 -56
  121. package/_site/_test/workbench-permission-test.js +117 -117
  122. package/_site/_test/workspace-ui-contract-test.js +28 -43
  123. package/_site/lib/ai-profile-resolver.js +78 -78
  124. package/_site/lib/ai-workspace.js +101 -101
  125. package/_site/lib/automation-config.js +140 -140
  126. package/_site/lib/bridge-adapter.js +5 -1
  127. package/_site/lib/bridge-consumer-service.js +402 -402
  128. package/_site/lib/claude-cli-runner.js +1510 -1510
  129. package/_site/lib/commit-conversation-binder.js +234 -234
  130. package/_site/lib/commit-processing-ledger.js +27 -27
  131. package/_site/lib/commit-prompt.js +202 -202
  132. package/_site/lib/commit-reconciler.js +406 -406
  133. package/_site/lib/contracts.js +284 -279
  134. package/_site/lib/conversation-query-service.js +144 -144
  135. package/_site/lib/conversation-store.js +385 -385
  136. package/_site/lib/data-dir.js +74 -74
  137. package/_site/lib/data-state-classifier.js +40 -40
  138. package/_site/lib/engine-cutover.js +97 -0
  139. package/_site/lib/evidence-bundle.js +228 -228
  140. package/_site/lib/folder-picker-output.js +21 -21
  141. package/_site/lib/git-runner.js +62 -62
  142. package/_site/lib/github-team-store.js +1172 -1172
  143. package/_site/lib/hook-manager.js +203 -202
  144. package/_site/lib/index-service.js +173 -173
  145. package/_site/lib/integration-installer.js +907 -907
  146. package/_site/lib/kb-framework.js +176 -176
  147. package/_site/lib/kb-validator.js +124 -124
  148. package/_site/lib/knowledge-promotion.js +435 -435
  149. package/_site/lib/knowledge-retrieval-service.js +401 -401
  150. package/_site/lib/knowledge-tool-runtime.js +359 -359
  151. package/_site/lib/legacy-data-manifest.js +26 -26
  152. package/_site/lib/llm-client.js +161 -161
  153. package/_site/lib/markdown-knowledge-indexer.js +230 -230
  154. package/_site/lib/migration-service.js +442 -442
  155. package/_site/lib/module-bridge.js +198 -33
  156. package/_site/lib/post-commit-automation.js +87 -87
  157. package/_site/lib/project-lifecycle-service.js +519 -497
  158. package/_site/lib/project-store.js +268 -262
  159. package/_site/lib/requirement-recorder.js +278 -278
  160. package/_site/lib/runtime-endpoint.js +155 -155
  161. package/_site/lib/scanner.js +298 -298
  162. package/_site/lib/server-app.js +1590 -1520
  163. package/_site/lib/settings-store.js +133 -113
  164. package/_site/lib/storage-layout.js +162 -162
  165. package/_site/lib/structured-logger.js +574 -574
  166. package/_site/scripts/folder-picker.ps1 +156 -156
  167. package/_site/scripts/hook-trigger.js +157 -156
  168. package/_site/scripts/install-module-candidates.js +69 -0
  169. package/_site/scripts/pack-module-candidates.js +72 -0
  170. package/_site/scripts/sync-release-version.js +2 -2
  171. package/_site/scripts/vendor-modules.js +47 -0
  172. package/_site/scripts/verify-module-runtime.js +45 -0
  173. package/_site/scripts/verify-product-runtime.js +34 -0
  174. package/bin/project-knowledge-mcp.js +194 -194
  175. package/docs/README.zh-CN.md +34 -25
  176. package/docs/project-registry-schema.md +22 -22
  177. package/docs/testing-strategy.md +33 -33
  178. package/module-runtime-manifest.json +220 -0
  179. package/package.json +13 -10
  180. package/plugins/project-knowledge/.claude-plugin/plugin.json +1 -1
  181. package/plugins/project-knowledge/.codex-plugin/plugin.json +1 -1
  182. package/plugins/project-knowledge/.mcp.json +1 -1
  183. package/plugins/project-knowledge/opencode/project-knowledge.md +3 -3
  184. package/plugins/project-knowledge/skills/project-knowledge/SKILL.md +28 -28
  185. package/templates/project-readme.md +34 -34
  186. package/ui/favicon.svg +38 -38
  187. package/ui/index.html +51 -149
  188. package/ui/product.css +9 -0
  189. package/ui/product.js +386 -0
  190. package/vendor-manifest.json +46 -0
  191. package/_site/_test/import-ui-flow-test.js +0 -171
  192. package/_site/_test/project-control-panel-task14-test.js +0 -63
  193. package/_site/_test/task15-20-ui-flow-test.js +0 -148
  194. package/_site/_test/ui-i18n-toggle-test.js +0 -114
  195. package/_site/_test/ui-smoke-test.js +0 -73
  196. package/ui/app.css +0 -58
  197. package/ui/app.js +0 -607
  198. package/ui/i18n.js +0 -146
@@ -1,574 +1,574 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const crypto = require('crypto');
4
- const { EventEmitter } = require('events');
5
- const {
6
- SCHEMAS,
7
- LOG_LEVELS,
8
- REDACTION_KEY_PATTERN,
9
- REDACTED_VALUE,
10
- FIELD_LIMITS,
11
- DomainError,
12
- createId,
13
- } = require('./contracts');
14
- const { StorageLayout } = require('./storage-layout');
15
- const AtomicFile = require('./atomic-file');
16
-
17
- const SCHEMA = SCHEMAS.log;
18
- const LEVELS = new Set(LOG_LEVELS);
19
- const CURSOR_VERSION = 2;
20
- const DEFAULT_PAGE_SIZE = 500;
21
- const MAX_PAGE_SIZE = 5000;
22
- const REVERSE_CHUNK_BYTES = 64 * 1024;
23
- const TERMINAL_EVENTS = /\.(?:completed|failed|cancelled)$/;
24
-
25
- function localDay(date = new Date()) {
26
- const value = date instanceof Date ? date : new Date(date);
27
- const valid = Number.isNaN(value.getTime()) ? new Date() : value;
28
- const year = valid.getFullYear();
29
- const month = String(valid.getMonth() + 1).padStart(2, '0');
30
- const day = String(valid.getDate()).padStart(2, '0');
31
- return `${year}-${month}-${day}`;
32
- }
33
-
34
- function defaultConfig(appRoot) {
35
- return {
36
- schema: SCHEMA,
37
- rootPath: path.join(path.resolve(appRoot), 'logs'),
38
- levels: [...LOG_LEVELS],
39
- configured: false,
40
- };
41
- }
42
-
43
- function normalizeConfig(input, appRoot) {
44
- const source = input && typeof input === 'object' ? input : {};
45
- const levels = Array.isArray(source.levels) ? source.levels.filter(level => LEVELS.has(level)) : [];
46
- return {
47
- schema: SCHEMA,
48
- rootPath: path.join(path.resolve(appRoot), 'logs'),
49
- levels: levels.length ? [...new Set(levels)] : [...LOG_LEVELS],
50
- configured: source.configured === true,
51
- };
52
- }
53
-
54
- function readConfig(configPath, appRoot) {
55
- if (!fs.existsSync(configPath)) return defaultConfig(appRoot);
56
- try { return normalizeConfig(JSON.parse(fs.readFileSync(configPath, 'utf8')), appRoot); }
57
- catch (error) { throw new DomainError('DATA_CORRUPT', 'Logging configuration is corrupt.', { status: 500, cause: error }); }
58
- }
59
-
60
- function writeConfig(configPath, appRoot, config) {
61
- const normalized = normalizeConfig({ ...(config || {}), configured: true }, appRoot);
62
- AtomicFile.writeJsonAtomic(configPath, normalized);
63
- return normalized;
64
- }
65
-
66
- function boundedString(value, limit = FIELD_LIMITS.contextString) {
67
- const text = String(value == null ? '' : value);
68
- return text.length > limit ? `${text.slice(0, limit)}…[truncated:${text.length - limit}]` : text;
69
- }
70
-
71
- function redactString(value, secrets = []) {
72
- let text = boundedString(value);
73
- for (const secret of secrets || []) {
74
- if (typeof secret === 'string' && secret.length >= 4) text = text.split(secret).join(REDACTED_VALUE);
75
- }
76
- return text
77
- .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=:-]+/gi, `$1 ${REDACTED_VALUE}`)
78
- .replace(/([?&](?:api[-_]?key|token|access_token|auth|secret)=)[^&#\s]+/gi, `$1${REDACTED_VALUE}`)
79
- .replace(/(https?:\/\/[^\s/:@]+:)[^\s/@]+@/gi, `$1${REDACTED_VALUE}@`);
80
- }
81
-
82
- function redactValue(value, options = {}, key = '', seen = new WeakSet()) {
83
- const secrets = options.secrets || [];
84
- if (REDACTION_KEY_PATTERN.test(key) || /(?:headers?|prompt|diff|requestBody|responseBody)/i.test(key)) return REDACTED_VALUE;
85
- if (value == null || typeof value === 'boolean' || typeof value === 'number') return value;
86
- if (typeof value === 'string') return redactString(value, secrets);
87
- if (value instanceof Error) return serializeError(value, options, seen);
88
- if (typeof value !== 'object') return redactString(value, secrets);
89
- if (seen.has(value)) return '[Circular]';
90
- seen.add(value);
91
- if (Array.isArray(value)) return value.slice(0, 200).map(item => redactValue(item, options, '', seen));
92
- const output = {};
93
- for (const [childKey, child] of Object.entries(value)) output[childKey] = redactValue(child, options, childKey, seen);
94
- return output;
95
- }
96
-
97
- function serializeError(error, options = {}, seen = new WeakSet()) {
98
- if (!error) return null;
99
- if (seen.has(error)) return { name: 'Error', message: '[Circular error]' };
100
- seen.add(error);
101
- const output = {
102
- name: boundedString(error.name || 'Error', 256),
103
- code: boundedString(error.code || '', 256),
104
- message: redactString(boundedString(error.message || error, FIELD_LIMITS.message), options.secrets),
105
- stack: redactString(boundedString(error.stack || '', FIELD_LIMITS.stack), options.secrets),
106
- };
107
- if (error.cause) output.cause = error.cause instanceof Error
108
- ? serializeError(error.cause, options, seen)
109
- : redactValue(error.cause, options, 'cause', seen);
110
- return output;
111
- }
112
-
113
- function normalizeRecord(entry, options = {}) {
114
- const context = entry.context && typeof entry.context === 'object'
115
- ? entry.context
116
- : (entry.meta && typeof entry.meta === 'object' ? entry.meta : {});
117
- return {
118
- schema: SCHEMA,
119
- id: entry.id || createId('log'),
120
- ts: entry.ts || new Date().toISOString(),
121
- level: LEVELS.has(entry.level) ? entry.level : 'info',
122
- component: boundedString(entry.component || entry.source || 'app', 256),
123
- event: boundedString(entry.event || 'message', 256),
124
- message: redactString(boundedString(entry.message || '', FIELD_LIMITS.message), options.secrets),
125
- projectId: boundedString(entry.projectId || '', 128),
126
- projectSlug: boundedString(entry.projectSlug || '', 128),
127
- projectDisplayName: boundedString(entry.projectDisplayName || '', 256),
128
- projectDeleted: entry.projectDeleted === true,
129
- operationId: boundedString(entry.operationId || '', 128),
130
- jobId: boundedString(entry.jobId || '', 128),
131
- runId: boundedString(entry.runId || '', 128),
132
- commitSha: boundedString(entry.commitSha || entry.commitHash || '', 128),
133
- phase: boundedString(entry.phase || '', 128),
134
- attempt: Number.isFinite(entry.attempt) ? Number(entry.attempt) : 0,
135
- durationMs: Number.isFinite(entry.durationMs) ? Number(entry.durationMs) : 0,
136
- error: entry.error ? serializeError(entry.error, options) : null,
137
- context: redactValue(context, options, 'context'),
138
- };
139
- }
140
-
141
- function appendRecordSync(directory, record, options = {}) {
142
- fs.mkdirSync(directory, { recursive: true });
143
- const filePath = path.join(directory, `${localDay(record.ts)}.jsonl`);
144
- const line = Buffer.from(`${JSON.stringify(record)}\n`, 'utf8');
145
- const fd = fs.openSync(filePath, 'a', 0o600);
146
- try {
147
- fs.writeSync(fd, line, 0, line.length, null);
148
- if (options.flush !== false) fs.fsyncSync(fd);
149
- } finally {
150
- fs.closeSync(fd);
151
- }
152
- return filePath;
153
- }
154
-
155
- function createLoggerCore(stderr) {
156
- return {
157
- queue: Promise.resolve(),
158
- health: { status: 'ok', lastError: null, failedAt: '', suppressedLevels: [] },
159
- events: new EventEmitter(),
160
- stderr,
161
- };
162
- }
163
-
164
- class Logger {
165
- constructor(options = {}) {
166
- this.layout = options.layout || new StorageLayout(options);
167
- this.settingsProvider = options.settingsProvider || (() => defaultConfig(this.layout.getDataDir()));
168
- this.projectId = options.projectId || '';
169
- this.baseContext = Object.freeze({ ...(options.context || {}) });
170
- this.secrets = options.secrets || [];
171
- this.secretsProvider = typeof options.secretsProvider === 'function' ? options.secretsProvider : null;
172
- this.core = options.core || createLoggerCore(options.stderr || process.stderr);
173
- }
174
-
175
- child(context = {}) {
176
- return new Logger({
177
- layout: this.layout,
178
- settingsProvider: this.settingsProvider,
179
- projectId: context.projectId || this.projectId,
180
- context: { ...this.baseContext, ...context },
181
- secrets: this.secrets,
182
- secretsProvider: this.secretsProvider,
183
- core: this.core,
184
- });
185
- }
186
-
187
- currentSecrets() {
188
- let dynamic = [];
189
- try { dynamic = this.secretsProvider ? this.secretsProvider() : []; }
190
- catch { dynamic = []; }
191
- return [...new Set([...this.secrets, ...(Array.isArray(dynamic) ? dynamic : [])]
192
- .filter(secret => typeof secret === 'string' && secret.length >= 4))];
193
- }
194
-
195
- directoryFor(record) {
196
- const projectId = record.projectId || this.projectId;
197
- return projectId ? this.layout.getLogPath('project', projectId) : this.layout.getLogPath('system');
198
- }
199
-
200
- isEnabled(level) {
201
- const config = normalizeConfig(this.settingsProvider() || {}, this.layout.getDataDir());
202
- return config.levels.includes(level) && !this.core.health.suppressedLevels.includes(level);
203
- }
204
-
205
- log(level, event, message, input = {}) {
206
- if (!LEVELS.has(level)) throw new DomainError('INVALID_ARGUMENT', `Invalid log level: ${level}.`);
207
- if (!this.isEnabled(level)) return Promise.resolve(null);
208
- const merged = { ...this.baseContext, ...(input || {}) };
209
- const secrets = this.currentSecrets();
210
- const record = normalizeRecord({
211
- ...merged,
212
- level,
213
- event,
214
- message,
215
- projectId: merged.projectId || this.projectId,
216
- context: merged.context || merged.meta || {},
217
- }, { secrets });
218
- const operation = async () => {
219
- try {
220
- const file = appendRecordSync(this.directoryFor(record), record);
221
- for (const listener of this.core.events.listeners('log-appended')) {
222
- try { listener(record); }
223
- catch {
224
- // Subscribers are observers and cannot affect durable logging.
225
- }
226
- }
227
- return { file, record };
228
- } catch (error) {
229
- this.core.health.status = 'degraded';
230
- this.core.health.lastError = serializeError(error, { secrets });
231
- this.core.health.failedAt = new Date().toISOString();
232
- this.core.health.suppressedLevels = ['trace', 'debug'];
233
- const fallback = normalizeRecord({ ...record, error: record.error || error }, { secrets });
234
- try { this.core.stderr.write(`[project-knowledge logger fallback] ${JSON.stringify(fallback)}\n`); }
235
- catch {
236
- // stderr is the logger's final non-recursive fallback.
237
- }
238
- return null;
239
- }
240
- };
241
- this.core.queue = this.core.queue.then(operation, operation);
242
- return this.core.queue;
243
- }
244
-
245
- trace(event, message, context) { return this.log('trace', event, message, context); }
246
- debug(event, message, context) { return this.log('debug', event, message, context); }
247
- info(event, message, context) { return this.log('info', event, message, context); }
248
- warn(event, message, context) { return this.log('warn', event, message, context); }
249
- error(event, message, context) { return this.log('error', event, message, context); }
250
- fatal(event, message, context) { return this.log('fatal', event, message, context); }
251
- subscribe(listener) {
252
- if (typeof listener !== 'function') throw new DomainError('INVALID_ARGUMENT', 'Log subscriber must be a function.');
253
- this.core.events.on('log-appended', listener);
254
- return () => this.core.events.off('log-appended', listener);
255
- }
256
- flush() { return this.core.queue; }
257
- close() { return this.flush(); }
258
- getHealth() { return JSON.parse(JSON.stringify(this.core.health)); }
259
- }
260
-
261
- function parseLogDate(fileName) {
262
- const match = String(fileName).match(/^(\d{4}-\d{2}-\d{2})(?:\.\d{3})?\.(?:jsonl|log)$/);
263
- return match ? match[1] : '';
264
- }
265
-
266
- function parseLine(line, sourceFile) {
267
- try {
268
- const parsed = JSON.parse(line);
269
- if (!parsed || !parsed.ts) return null;
270
- if (parsed.schema === SCHEMA) return { ...parsed, file: sourceFile };
271
- return {
272
- ...normalizeRecord({
273
- ts: parsed.ts,
274
- level: parsed.level,
275
- event: parsed.event,
276
- message: parsed.message,
277
- component: parsed.source || parsed.component || 'legacy',
278
- projectId: parsed.projectId,
279
- projectSlug: parsed.projectSlug,
280
- projectDisplayName: parsed.projectDisplayName,
281
- operationId: parsed.operationId,
282
- jobId: parsed.jobId,
283
- runId: parsed.runId,
284
- commitSha: parsed.commitSha || parsed.commitHash,
285
- context: parsed.meta || parsed.context || {},
286
- }),
287
- file: sourceFile,
288
- };
289
- } catch {
290
- return null;
291
- }
292
- }
293
-
294
- function encodeCursor(value) { return Buffer.from(JSON.stringify(value)).toString('base64url'); }
295
- function decodeCursor(value) {
296
- try { return JSON.parse(Buffer.from(String(value), 'base64url').toString('utf8')); }
297
- catch { throw new DomainError('INVALID_ARGUMENT', 'Invalid log cursor.', { status: 400 }); }
298
- }
299
-
300
- function filterFingerprint(filters) {
301
- const stable = {};
302
- for (const key of ['from', 'to', 'levels', 'scope', 'projectId', 'component', 'event', 'commitSha', 'operationId', 'q', 'pageSize']) stable[key] = filters[key] || '';
303
- return crypto.createHash('sha256').update(JSON.stringify(stable)).digest('hex').slice(0, 20);
304
- }
305
-
306
- function readPreviousLine(fd, endOffset) {
307
- let end = Math.max(0, Number(endOffset || 0));
308
- const one = Buffer.allocUnsafe(1);
309
- while (end > 0) {
310
- fs.readSync(fd, one, 0, 1, end - 1);
311
- if (one[0] !== 0x0a && one[0] !== 0x0d) break;
312
- end -= 1;
313
- }
314
- if (end === 0) return null;
315
- let cursor = end;
316
- while (cursor > 0) {
317
- const start = Math.max(0, cursor - REVERSE_CHUNK_BYTES);
318
- const buffer = Buffer.allocUnsafe(cursor - start);
319
- fs.readSync(fd, buffer, 0, buffer.length, start);
320
- for (let index = buffer.length - 1; index >= 0; index -= 1) {
321
- if (buffer[index] === 0x0a) {
322
- const lineStart = start + index + 1;
323
- const lineBuffer = Buffer.allocUnsafe(end - lineStart);
324
- fs.readSync(fd, lineBuffer, 0, lineBuffer.length, lineStart);
325
- return { line: lineBuffer.toString('utf8').replace(/\r$/, ''), nextOffset: lineStart };
326
- }
327
- }
328
- cursor = start;
329
- }
330
- const lineBuffer = Buffer.allocUnsafe(end);
331
- fs.readSync(fd, lineBuffer, 0, end, 0);
332
- return { line: lineBuffer.toString('utf8').replace(/\r$/, ''), nextOffset: 0 };
333
- }
334
-
335
- class LogRepository {
336
- constructor(options = {}) {
337
- this.layout = options.layout || new StorageLayout(options);
338
- this.secrets = options.secrets || [];
339
- this.secretsProvider = typeof options.secretsProvider === 'function' ? options.secretsProvider : null;
340
- }
341
-
342
- currentSecrets() {
343
- let dynamic = [];
344
- try { dynamic = this.secretsProvider ? this.secretsProvider() : []; }
345
- catch { dynamic = []; }
346
- return [...new Set([...this.secrets, ...(Array.isArray(dynamic) ? dynamic : [])]
347
- .filter(secret => typeof secret === 'string' && secret.length >= 4))];
348
- }
349
-
350
- listSources() {
351
- const root = path.join(this.layout.getDataDir(), 'logs');
352
- if (!fs.existsSync(root)) return [];
353
- const output = [];
354
- const visit = directory => {
355
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
356
- const absolute = path.join(directory, entry.name);
357
- if (entry.isDirectory()) visit(absolute);
358
- else if (entry.isFile() && parseLogDate(entry.name)) {
359
- const stat = fs.statSync(absolute);
360
- output.push({
361
- path: absolute,
362
- relative: path.relative(root, absolute).replace(/\\/g, '/'),
363
- date: parseLogDate(entry.name),
364
- size: stat.size,
365
- });
366
- }
367
- }
368
- };
369
- visit(root);
370
- return output.sort((left, right) => left.relative.localeCompare(right.relative));
371
- }
372
-
373
- matches(record, filters) {
374
- const recordDay = localDay(record.ts);
375
- if (filters.from && recordDay < filters.from) return false;
376
- if (filters.to && recordDay > filters.to) return false;
377
- const levels = Array.isArray(filters.levels) ? filters.levels : String(filters.levels || '').split(',').filter(Boolean);
378
- if (levels.length && !levels.includes(record.level)) return false;
379
- if (filters.scope === 'system' && record.projectId) return false;
380
- if (filters.scope === 'project' && !record.projectId) return false;
381
- if (filters.projectId && filters.projectId !== record.projectId) return false;
382
- if (filters.component && filters.component !== record.component) return false;
383
- if (filters.event && filters.event !== record.event) return false;
384
- if (filters.commitSha && filters.commitSha !== record.commitSha) return false;
385
- if (filters.operationId && filters.operationId !== record.operationId) return false;
386
- if (filters.q) {
387
- const haystack = `${record.message} ${record.event} ${record.component} ${record.projectId} ${record.projectSlug} ${record.commitSha} ${record.operationId} ${JSON.stringify(record.context || {})}`.toLowerCase();
388
- if (!haystack.includes(String(filters.q).toLowerCase())) return false;
389
- }
390
- return true;
391
- }
392
-
393
- cursorExpired(message = 'Log cursor expired; restart the query.') {
394
- return new DomainError('LOG_CURSOR_EXPIRED', message, { status: 409, retryable: true });
395
- }
396
-
397
- query(input = {}) {
398
- const today = localDay();
399
- const pageSize = Math.max(1, Math.min(Number(input.pageSize || DEFAULT_PAGE_SIZE), MAX_PAGE_SIZE));
400
- const filters = { ...input, from: input.from || today, to: input.to || today, pageSize };
401
- const fingerprint = filterFingerprint(filters);
402
- const root = path.join(this.layout.getDataDir(), 'logs');
403
- let states;
404
- if (input.cursor) {
405
- const cursor = decodeCursor(input.cursor);
406
- if (cursor.v !== CURSOR_VERSION || cursor.f !== fingerprint || !Array.isArray(cursor.sources)) {
407
- throw this.cursorExpired('Log cursor does not match the current filters.');
408
- }
409
- states = cursor.sources.map(source => {
410
- const filePath = path.resolve(root, source.path);
411
- const relative = path.relative(root, filePath);
412
- if (relative.startsWith('..') || path.isAbsolute(relative) || !fs.existsSync(filePath)) throw this.cursorExpired();
413
- const size = fs.statSync(filePath).size;
414
- if (size < source.limit || source.offset > source.limit) throw this.cursorExpired();
415
- return { path: filePath, relative: source.path, limit: source.limit, offset: source.offset };
416
- });
417
- } else {
418
- states = this.listSources()
419
- .filter(source => source.date >= filters.from && source.date <= filters.to)
420
- .map(source => ({ path: source.path, relative: source.relative, limit: source.size, offset: source.size }));
421
- }
422
-
423
- const openStates = states.map(state => ({ ...state, fd: fs.openSync(state.path, 'r') }));
424
- const candidates = [];
425
- const loadCandidate = state => {
426
- while (state.offset > 0) {
427
- const previous = readPreviousLine(state.fd, state.offset);
428
- if (!previous) { state.offset = 0; return; }
429
- const record = parseLine(previous.line, state.relative);
430
- if (!record || !this.matches(record, filters)) {
431
- state.offset = previous.nextOffset;
432
- continue;
433
- }
434
- candidates.push({ state, record, nextOffset: previous.nextOffset });
435
- return;
436
- }
437
- };
438
-
439
- try {
440
- for (const state of openStates) loadCandidate(state);
441
- const entries = [];
442
- while (entries.length < pageSize && candidates.length) {
443
- candidates.sort((left, right) => String(right.record.ts).localeCompare(String(left.record.ts))
444
- || String(right.record.id).localeCompare(String(left.record.id))
445
- || right.state.relative.localeCompare(left.state.relative));
446
- const selected = candidates.shift();
447
- entries.push(redactValue(selected.record, { secrets: this.currentSecrets() }));
448
- selected.state.offset = selected.nextOffset;
449
- loadCandidate(selected.state);
450
- }
451
- const nextCursor = candidates.length
452
- ? encodeCursor({
453
- v: CURSOR_VERSION,
454
- f: fingerprint,
455
- sources: openStates.map(state => ({ path: state.relative, limit: state.limit, offset: state.offset })),
456
- })
457
- : null;
458
- return {
459
- entries,
460
- nextCursor,
461
- pageSize,
462
- from: filters.from,
463
- to: filters.to,
464
- counts: this.countLevels(entries),
465
- };
466
- } finally {
467
- for (const state of openStates) fs.closeSync(state.fd);
468
- }
469
- }
470
-
471
- countLevels(entries) {
472
- return Object.fromEntries(LOG_LEVELS.map(level => [level, entries.filter(entry => entry.level === level).length]));
473
- }
474
-
475
- exportToFile(filePath, filters = {}) {
476
- let cursor = '';
477
- let count = 0;
478
- const secrets = this.currentSecrets();
479
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
480
- const fd = fs.openSync(filePath, 'w', 0o600);
481
- try {
482
- do {
483
- const page = this.query({ ...filters, cursor, pageSize: 1000 });
484
- for (const entry of page.entries) {
485
- fs.writeSync(fd, `${JSON.stringify(redactValue(entry, { secrets }))}\n`, null, 'utf8');
486
- count += 1;
487
- }
488
- cursor = page.nextCursor || '';
489
- } while (cursor);
490
- fs.fsyncSync(fd);
491
- } finally {
492
- fs.closeSync(fd);
493
- }
494
- return { filePath, count };
495
- }
496
-
497
- findOrphanedOperations(filters = {}) {
498
- const starts = new Map();
499
- const completed = new Set();
500
- let cursor = '';
501
- let inspected = 0;
502
- const maxEntries = Math.max(1, Math.min(Number(filters.maxEntries || 10000), 50000));
503
- do {
504
- const page = this.query({ ...filters, cursor, pageSize: Math.min(1000, maxEntries - inspected) });
505
- for (const entry of page.entries) {
506
- inspected += 1;
507
- if (!entry.operationId) continue;
508
- if (/\.started$/.test(entry.event)) starts.set(entry.operationId, entry);
509
- if (TERMINAL_EVENTS.test(entry.event)) completed.add(entry.operationId);
510
- }
511
- cursor = inspected < maxEntries ? (page.nextCursor || '') : '';
512
- } while (cursor);
513
- return [...starts.entries()].filter(([operationId]) => !completed.has(operationId)).map(([, entry]) => entry);
514
- }
515
- }
516
-
517
- function appendLog(configPath, appRoot, entry) {
518
- const config = readConfig(configPath, appRoot);
519
- const level = LEVELS.has(entry.level) ? entry.level : 'info';
520
- if (!config.levels.includes(level)) return null;
521
- const record = normalizeRecord({
522
- ...entry,
523
- level,
524
- component: entry.component || entry.source || 'server',
525
- context: entry.context || entry.meta || {},
526
- });
527
- const file = appendRecordSync(path.join(config.rootPath, 'system'), record);
528
- return { file, record };
529
- }
530
-
531
- function readLogs(configPath, appRoot, filters = {}) {
532
- const layout = new StorageLayout({ dataDir: appRoot });
533
- const repository = new LogRepository({ layout });
534
- const result = repository.query({
535
- from: filters.from || filters.dateFrom || '',
536
- to: filters.to || filters.dateTo || '',
537
- levels: filters.levels || (filters.level && filters.level !== 'all' ? [filters.level] : []),
538
- scope: filters.scope || '',
539
- projectId: filters.projectId || '',
540
- component: filters.component || (filters.source && filters.source !== 'all' ? filters.source : ''),
541
- event: filters.event || '',
542
- commitSha: filters.commitSha || '',
543
- operationId: filters.operationId || '',
544
- q: filters.q || '',
545
- pageSize: filters.pageSize || filters.limit || DEFAULT_PAGE_SIZE,
546
- cursor: filters.cursor || '',
547
- });
548
- if (filters.returnPage) return result;
549
- if (filters.projectSlug && filters.projectSlug !== 'all') return result.entries.filter(entry => entry.projectSlug === filters.projectSlug);
550
- return result.entries;
551
- }
552
-
553
- module.exports = {
554
- SCHEMA,
555
- LEVELS,
556
- DEFAULT_PAGE_SIZE,
557
- MAX_PAGE_SIZE,
558
- Logger,
559
- LogRepository,
560
- defaultConfig,
561
- normalizeConfig,
562
- readConfig,
563
- writeConfig,
564
- appendLog,
565
- readLogs,
566
- normalizeRecord,
567
- appendRecordSync,
568
- redactString,
569
- redactValue,
570
- serializeError,
571
- parseLine,
572
- localDay,
573
- readPreviousLine,
574
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { EventEmitter } = require('events');
5
+ const {
6
+ SCHEMAS,
7
+ LOG_LEVELS,
8
+ REDACTION_KEY_PATTERN,
9
+ REDACTED_VALUE,
10
+ FIELD_LIMITS,
11
+ DomainError,
12
+ createId,
13
+ } = require('./contracts');
14
+ const { StorageLayout } = require('./storage-layout');
15
+ const AtomicFile = require('./atomic-file');
16
+
17
+ const SCHEMA = SCHEMAS.log;
18
+ const LEVELS = new Set(LOG_LEVELS);
19
+ const CURSOR_VERSION = 2;
20
+ const DEFAULT_PAGE_SIZE = 500;
21
+ const MAX_PAGE_SIZE = 5000;
22
+ const REVERSE_CHUNK_BYTES = 64 * 1024;
23
+ const TERMINAL_EVENTS = /\.(?:completed|failed|cancelled)$/;
24
+
25
+ function localDay(date = new Date()) {
26
+ const value = date instanceof Date ? date : new Date(date);
27
+ const valid = Number.isNaN(value.getTime()) ? new Date() : value;
28
+ const year = valid.getFullYear();
29
+ const month = String(valid.getMonth() + 1).padStart(2, '0');
30
+ const day = String(valid.getDate()).padStart(2, '0');
31
+ return `${year}-${month}-${day}`;
32
+ }
33
+
34
+ function defaultConfig(appRoot) {
35
+ return {
36
+ schema: SCHEMA,
37
+ rootPath: path.join(path.resolve(appRoot), 'logs'),
38
+ levels: [...LOG_LEVELS],
39
+ configured: false,
40
+ };
41
+ }
42
+
43
+ function normalizeConfig(input, appRoot) {
44
+ const source = input && typeof input === 'object' ? input : {};
45
+ const levels = Array.isArray(source.levels) ? source.levels.filter(level => LEVELS.has(level)) : [];
46
+ return {
47
+ schema: SCHEMA,
48
+ rootPath: path.join(path.resolve(appRoot), 'logs'),
49
+ levels: levels.length ? [...new Set(levels)] : [...LOG_LEVELS],
50
+ configured: source.configured === true,
51
+ };
52
+ }
53
+
54
+ function readConfig(configPath, appRoot) {
55
+ if (!fs.existsSync(configPath)) return defaultConfig(appRoot);
56
+ try { return normalizeConfig(JSON.parse(fs.readFileSync(configPath, 'utf8')), appRoot); }
57
+ catch (error) { throw new DomainError('DATA_CORRUPT', 'Logging configuration is corrupt.', { status: 500, cause: error }); }
58
+ }
59
+
60
+ function writeConfig(configPath, appRoot, config) {
61
+ const normalized = normalizeConfig({ ...(config || {}), configured: true }, appRoot);
62
+ AtomicFile.writeJsonAtomic(configPath, normalized);
63
+ return normalized;
64
+ }
65
+
66
+ function boundedString(value, limit = FIELD_LIMITS.contextString) {
67
+ const text = String(value == null ? '' : value);
68
+ return text.length > limit ? `${text.slice(0, limit)}…[truncated:${text.length - limit}]` : text;
69
+ }
70
+
71
+ function redactString(value, secrets = []) {
72
+ let text = boundedString(value);
73
+ for (const secret of secrets || []) {
74
+ if (typeof secret === 'string' && secret.length >= 4) text = text.split(secret).join(REDACTED_VALUE);
75
+ }
76
+ return text
77
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=:-]+/gi, `$1 ${REDACTED_VALUE}`)
78
+ .replace(/([?&](?:api[-_]?key|token|access_token|auth|secret)=)[^&#\s]+/gi, `$1${REDACTED_VALUE}`)
79
+ .replace(/(https?:\/\/[^\s/:@]+:)[^\s/@]+@/gi, `$1${REDACTED_VALUE}@`);
80
+ }
81
+
82
+ function redactValue(value, options = {}, key = '', seen = new WeakSet()) {
83
+ const secrets = options.secrets || [];
84
+ if (REDACTION_KEY_PATTERN.test(key) || /(?:headers?|prompt|diff|requestBody|responseBody)/i.test(key)) return REDACTED_VALUE;
85
+ if (value == null || typeof value === 'boolean' || typeof value === 'number') return value;
86
+ if (typeof value === 'string') return redactString(value, secrets);
87
+ if (value instanceof Error) return serializeError(value, options, seen);
88
+ if (typeof value !== 'object') return redactString(value, secrets);
89
+ if (seen.has(value)) return '[Circular]';
90
+ seen.add(value);
91
+ if (Array.isArray(value)) return value.slice(0, 200).map(item => redactValue(item, options, '', seen));
92
+ const output = {};
93
+ for (const [childKey, child] of Object.entries(value)) output[childKey] = redactValue(child, options, childKey, seen);
94
+ return output;
95
+ }
96
+
97
+ function serializeError(error, options = {}, seen = new WeakSet()) {
98
+ if (!error) return null;
99
+ if (seen.has(error)) return { name: 'Error', message: '[Circular error]' };
100
+ seen.add(error);
101
+ const output = {
102
+ name: boundedString(error.name || 'Error', 256),
103
+ code: boundedString(error.code || '', 256),
104
+ message: redactString(boundedString(error.message || error, FIELD_LIMITS.message), options.secrets),
105
+ stack: redactString(boundedString(error.stack || '', FIELD_LIMITS.stack), options.secrets),
106
+ };
107
+ if (error.cause) output.cause = error.cause instanceof Error
108
+ ? serializeError(error.cause, options, seen)
109
+ : redactValue(error.cause, options, 'cause', seen);
110
+ return output;
111
+ }
112
+
113
+ function normalizeRecord(entry, options = {}) {
114
+ const context = entry.context && typeof entry.context === 'object'
115
+ ? entry.context
116
+ : (entry.meta && typeof entry.meta === 'object' ? entry.meta : {});
117
+ return {
118
+ schema: SCHEMA,
119
+ id: entry.id || createId('log'),
120
+ ts: entry.ts || new Date().toISOString(),
121
+ level: LEVELS.has(entry.level) ? entry.level : 'info',
122
+ component: boundedString(entry.component || entry.source || 'app', 256),
123
+ event: boundedString(entry.event || 'message', 256),
124
+ message: redactString(boundedString(entry.message || '', FIELD_LIMITS.message), options.secrets),
125
+ projectId: boundedString(entry.projectId || '', 128),
126
+ projectSlug: boundedString(entry.projectSlug || '', 128),
127
+ projectDisplayName: boundedString(entry.projectDisplayName || '', 256),
128
+ projectDeleted: entry.projectDeleted === true,
129
+ operationId: boundedString(entry.operationId || '', 128),
130
+ jobId: boundedString(entry.jobId || '', 128),
131
+ runId: boundedString(entry.runId || '', 128),
132
+ commitSha: boundedString(entry.commitSha || entry.commitHash || '', 128),
133
+ phase: boundedString(entry.phase || '', 128),
134
+ attempt: Number.isFinite(entry.attempt) ? Number(entry.attempt) : 0,
135
+ durationMs: Number.isFinite(entry.durationMs) ? Number(entry.durationMs) : 0,
136
+ error: entry.error ? serializeError(entry.error, options) : null,
137
+ context: redactValue(context, options, 'context'),
138
+ };
139
+ }
140
+
141
+ function appendRecordSync(directory, record, options = {}) {
142
+ fs.mkdirSync(directory, { recursive: true });
143
+ const filePath = path.join(directory, `${localDay(record.ts)}.jsonl`);
144
+ const line = Buffer.from(`${JSON.stringify(record)}\n`, 'utf8');
145
+ const fd = fs.openSync(filePath, 'a', 0o600);
146
+ try {
147
+ fs.writeSync(fd, line, 0, line.length, null);
148
+ if (options.flush !== false) fs.fsyncSync(fd);
149
+ } finally {
150
+ fs.closeSync(fd);
151
+ }
152
+ return filePath;
153
+ }
154
+
155
+ function createLoggerCore(stderr) {
156
+ return {
157
+ queue: Promise.resolve(),
158
+ health: { status: 'ok', lastError: null, failedAt: '', suppressedLevels: [] },
159
+ events: new EventEmitter(),
160
+ stderr,
161
+ };
162
+ }
163
+
164
+ class Logger {
165
+ constructor(options = {}) {
166
+ this.layout = options.layout || new StorageLayout(options);
167
+ this.settingsProvider = options.settingsProvider || (() => defaultConfig(this.layout.getDataDir()));
168
+ this.projectId = options.projectId || '';
169
+ this.baseContext = Object.freeze({ ...(options.context || {}) });
170
+ this.secrets = options.secrets || [];
171
+ this.secretsProvider = typeof options.secretsProvider === 'function' ? options.secretsProvider : null;
172
+ this.core = options.core || createLoggerCore(options.stderr || process.stderr);
173
+ }
174
+
175
+ child(context = {}) {
176
+ return new Logger({
177
+ layout: this.layout,
178
+ settingsProvider: this.settingsProvider,
179
+ projectId: context.projectId || this.projectId,
180
+ context: { ...this.baseContext, ...context },
181
+ secrets: this.secrets,
182
+ secretsProvider: this.secretsProvider,
183
+ core: this.core,
184
+ });
185
+ }
186
+
187
+ currentSecrets() {
188
+ let dynamic = [];
189
+ try { dynamic = this.secretsProvider ? this.secretsProvider() : []; }
190
+ catch { dynamic = []; }
191
+ return [...new Set([...this.secrets, ...(Array.isArray(dynamic) ? dynamic : [])]
192
+ .filter(secret => typeof secret === 'string' && secret.length >= 4))];
193
+ }
194
+
195
+ directoryFor(record) {
196
+ const projectId = record.projectId || this.projectId;
197
+ return projectId ? this.layout.getLogPath('project', projectId) : this.layout.getLogPath('system');
198
+ }
199
+
200
+ isEnabled(level) {
201
+ const config = normalizeConfig(this.settingsProvider() || {}, this.layout.getDataDir());
202
+ return config.levels.includes(level) && !this.core.health.suppressedLevels.includes(level);
203
+ }
204
+
205
+ log(level, event, message, input = {}) {
206
+ if (!LEVELS.has(level)) throw new DomainError('INVALID_ARGUMENT', `Invalid log level: ${level}.`);
207
+ if (!this.isEnabled(level)) return Promise.resolve(null);
208
+ const merged = { ...this.baseContext, ...(input || {}) };
209
+ const secrets = this.currentSecrets();
210
+ const record = normalizeRecord({
211
+ ...merged,
212
+ level,
213
+ event,
214
+ message,
215
+ projectId: merged.projectId || this.projectId,
216
+ context: merged.context || merged.meta || {},
217
+ }, { secrets });
218
+ const operation = async () => {
219
+ try {
220
+ const file = appendRecordSync(this.directoryFor(record), record);
221
+ for (const listener of this.core.events.listeners('log-appended')) {
222
+ try { listener(record); }
223
+ catch {
224
+ // Subscribers are observers and cannot affect durable logging.
225
+ }
226
+ }
227
+ return { file, record };
228
+ } catch (error) {
229
+ this.core.health.status = 'degraded';
230
+ this.core.health.lastError = serializeError(error, { secrets });
231
+ this.core.health.failedAt = new Date().toISOString();
232
+ this.core.health.suppressedLevels = ['trace', 'debug'];
233
+ const fallback = normalizeRecord({ ...record, error: record.error || error }, { secrets });
234
+ try { this.core.stderr.write(`[project-knowledge logger fallback] ${JSON.stringify(fallback)}\n`); }
235
+ catch {
236
+ // stderr is the logger's final non-recursive fallback.
237
+ }
238
+ return null;
239
+ }
240
+ };
241
+ this.core.queue = this.core.queue.then(operation, operation);
242
+ return this.core.queue;
243
+ }
244
+
245
+ trace(event, message, context) { return this.log('trace', event, message, context); }
246
+ debug(event, message, context) { return this.log('debug', event, message, context); }
247
+ info(event, message, context) { return this.log('info', event, message, context); }
248
+ warn(event, message, context) { return this.log('warn', event, message, context); }
249
+ error(event, message, context) { return this.log('error', event, message, context); }
250
+ fatal(event, message, context) { return this.log('fatal', event, message, context); }
251
+ subscribe(listener) {
252
+ if (typeof listener !== 'function') throw new DomainError('INVALID_ARGUMENT', 'Log subscriber must be a function.');
253
+ this.core.events.on('log-appended', listener);
254
+ return () => this.core.events.off('log-appended', listener);
255
+ }
256
+ flush() { return this.core.queue; }
257
+ close() { return this.flush(); }
258
+ getHealth() { return JSON.parse(JSON.stringify(this.core.health)); }
259
+ }
260
+
261
+ function parseLogDate(fileName) {
262
+ const match = String(fileName).match(/^(\d{4}-\d{2}-\d{2})(?:\.\d{3})?\.(?:jsonl|log)$/);
263
+ return match ? match[1] : '';
264
+ }
265
+
266
+ function parseLine(line, sourceFile) {
267
+ try {
268
+ const parsed = JSON.parse(line);
269
+ if (!parsed || !parsed.ts) return null;
270
+ if (parsed.schema === SCHEMA) return { ...parsed, file: sourceFile };
271
+ return {
272
+ ...normalizeRecord({
273
+ ts: parsed.ts,
274
+ level: parsed.level,
275
+ event: parsed.event,
276
+ message: parsed.message,
277
+ component: parsed.source || parsed.component || 'legacy',
278
+ projectId: parsed.projectId,
279
+ projectSlug: parsed.projectSlug,
280
+ projectDisplayName: parsed.projectDisplayName,
281
+ operationId: parsed.operationId,
282
+ jobId: parsed.jobId,
283
+ runId: parsed.runId,
284
+ commitSha: parsed.commitSha || parsed.commitHash,
285
+ context: parsed.meta || parsed.context || {},
286
+ }),
287
+ file: sourceFile,
288
+ };
289
+ } catch {
290
+ return null;
291
+ }
292
+ }
293
+
294
+ function encodeCursor(value) { return Buffer.from(JSON.stringify(value)).toString('base64url'); }
295
+ function decodeCursor(value) {
296
+ try { return JSON.parse(Buffer.from(String(value), 'base64url').toString('utf8')); }
297
+ catch { throw new DomainError('INVALID_ARGUMENT', 'Invalid log cursor.', { status: 400 }); }
298
+ }
299
+
300
+ function filterFingerprint(filters) {
301
+ const stable = {};
302
+ for (const key of ['from', 'to', 'levels', 'scope', 'projectId', 'component', 'event', 'commitSha', 'operationId', 'q', 'pageSize']) stable[key] = filters[key] || '';
303
+ return crypto.createHash('sha256').update(JSON.stringify(stable)).digest('hex').slice(0, 20);
304
+ }
305
+
306
+ function readPreviousLine(fd, endOffset) {
307
+ let end = Math.max(0, Number(endOffset || 0));
308
+ const one = Buffer.allocUnsafe(1);
309
+ while (end > 0) {
310
+ fs.readSync(fd, one, 0, 1, end - 1);
311
+ if (one[0] !== 0x0a && one[0] !== 0x0d) break;
312
+ end -= 1;
313
+ }
314
+ if (end === 0) return null;
315
+ let cursor = end;
316
+ while (cursor > 0) {
317
+ const start = Math.max(0, cursor - REVERSE_CHUNK_BYTES);
318
+ const buffer = Buffer.allocUnsafe(cursor - start);
319
+ fs.readSync(fd, buffer, 0, buffer.length, start);
320
+ for (let index = buffer.length - 1; index >= 0; index -= 1) {
321
+ if (buffer[index] === 0x0a) {
322
+ const lineStart = start + index + 1;
323
+ const lineBuffer = Buffer.allocUnsafe(end - lineStart);
324
+ fs.readSync(fd, lineBuffer, 0, lineBuffer.length, lineStart);
325
+ return { line: lineBuffer.toString('utf8').replace(/\r$/, ''), nextOffset: lineStart };
326
+ }
327
+ }
328
+ cursor = start;
329
+ }
330
+ const lineBuffer = Buffer.allocUnsafe(end);
331
+ fs.readSync(fd, lineBuffer, 0, end, 0);
332
+ return { line: lineBuffer.toString('utf8').replace(/\r$/, ''), nextOffset: 0 };
333
+ }
334
+
335
+ class LogRepository {
336
+ constructor(options = {}) {
337
+ this.layout = options.layout || new StorageLayout(options);
338
+ this.secrets = options.secrets || [];
339
+ this.secretsProvider = typeof options.secretsProvider === 'function' ? options.secretsProvider : null;
340
+ }
341
+
342
+ currentSecrets() {
343
+ let dynamic = [];
344
+ try { dynamic = this.secretsProvider ? this.secretsProvider() : []; }
345
+ catch { dynamic = []; }
346
+ return [...new Set([...this.secrets, ...(Array.isArray(dynamic) ? dynamic : [])]
347
+ .filter(secret => typeof secret === 'string' && secret.length >= 4))];
348
+ }
349
+
350
+ listSources() {
351
+ const root = path.join(this.layout.getDataDir(), 'logs');
352
+ if (!fs.existsSync(root)) return [];
353
+ const output = [];
354
+ const visit = directory => {
355
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
356
+ const absolute = path.join(directory, entry.name);
357
+ if (entry.isDirectory()) visit(absolute);
358
+ else if (entry.isFile() && parseLogDate(entry.name)) {
359
+ const stat = fs.statSync(absolute);
360
+ output.push({
361
+ path: absolute,
362
+ relative: path.relative(root, absolute).replace(/\\/g, '/'),
363
+ date: parseLogDate(entry.name),
364
+ size: stat.size,
365
+ });
366
+ }
367
+ }
368
+ };
369
+ visit(root);
370
+ return output.sort((left, right) => left.relative.localeCompare(right.relative));
371
+ }
372
+
373
+ matches(record, filters) {
374
+ const recordDay = localDay(record.ts);
375
+ if (filters.from && recordDay < filters.from) return false;
376
+ if (filters.to && recordDay > filters.to) return false;
377
+ const levels = Array.isArray(filters.levels) ? filters.levels : String(filters.levels || '').split(',').filter(Boolean);
378
+ if (levels.length && !levels.includes(record.level)) return false;
379
+ if (filters.scope === 'system' && record.projectId) return false;
380
+ if (filters.scope === 'project' && !record.projectId) return false;
381
+ if (filters.projectId && filters.projectId !== record.projectId) return false;
382
+ if (filters.component && filters.component !== record.component) return false;
383
+ if (filters.event && filters.event !== record.event) return false;
384
+ if (filters.commitSha && filters.commitSha !== record.commitSha) return false;
385
+ if (filters.operationId && filters.operationId !== record.operationId) return false;
386
+ if (filters.q) {
387
+ const haystack = `${record.message} ${record.event} ${record.component} ${record.projectId} ${record.projectSlug} ${record.commitSha} ${record.operationId} ${JSON.stringify(record.context || {})} ${JSON.stringify(record.error || {})}`.toLowerCase();
388
+ if (!haystack.includes(String(filters.q).toLowerCase())) return false;
389
+ }
390
+ return true;
391
+ }
392
+
393
+ cursorExpired(message = 'Log cursor expired; restart the query.') {
394
+ return new DomainError('LOG_CURSOR_EXPIRED', message, { status: 409, retryable: true });
395
+ }
396
+
397
+ query(input = {}) {
398
+ const today = localDay();
399
+ const pageSize = Math.max(1, Math.min(Number(input.pageSize || DEFAULT_PAGE_SIZE), MAX_PAGE_SIZE));
400
+ const filters = { ...input, from: input.from || today, to: input.to || today, pageSize };
401
+ const fingerprint = filterFingerprint(filters);
402
+ const root = path.join(this.layout.getDataDir(), 'logs');
403
+ let states;
404
+ if (input.cursor) {
405
+ const cursor = decodeCursor(input.cursor);
406
+ if (cursor.v !== CURSOR_VERSION || cursor.f !== fingerprint || !Array.isArray(cursor.sources)) {
407
+ throw this.cursorExpired('Log cursor does not match the current filters.');
408
+ }
409
+ states = cursor.sources.map(source => {
410
+ const filePath = path.resolve(root, source.path);
411
+ const relative = path.relative(root, filePath);
412
+ if (relative.startsWith('..') || path.isAbsolute(relative) || !fs.existsSync(filePath)) throw this.cursorExpired();
413
+ const size = fs.statSync(filePath).size;
414
+ if (size < source.limit || source.offset > source.limit) throw this.cursorExpired();
415
+ return { path: filePath, relative: source.path, limit: source.limit, offset: source.offset };
416
+ });
417
+ } else {
418
+ states = this.listSources()
419
+ .filter(source => source.date >= filters.from && source.date <= filters.to)
420
+ .map(source => ({ path: source.path, relative: source.relative, limit: source.size, offset: source.size }));
421
+ }
422
+
423
+ const openStates = states.map(state => ({ ...state, fd: fs.openSync(state.path, 'r') }));
424
+ const candidates = [];
425
+ const loadCandidate = state => {
426
+ while (state.offset > 0) {
427
+ const previous = readPreviousLine(state.fd, state.offset);
428
+ if (!previous) { state.offset = 0; return; }
429
+ const record = parseLine(previous.line, state.relative);
430
+ if (!record || !this.matches(record, filters)) {
431
+ state.offset = previous.nextOffset;
432
+ continue;
433
+ }
434
+ candidates.push({ state, record, nextOffset: previous.nextOffset });
435
+ return;
436
+ }
437
+ };
438
+
439
+ try {
440
+ for (const state of openStates) loadCandidate(state);
441
+ const entries = [];
442
+ while (entries.length < pageSize && candidates.length) {
443
+ candidates.sort((left, right) => String(right.record.ts).localeCompare(String(left.record.ts))
444
+ || String(right.record.id).localeCompare(String(left.record.id))
445
+ || right.state.relative.localeCompare(left.state.relative));
446
+ const selected = candidates.shift();
447
+ entries.push(redactValue(selected.record, { secrets: this.currentSecrets() }));
448
+ selected.state.offset = selected.nextOffset;
449
+ loadCandidate(selected.state);
450
+ }
451
+ const nextCursor = candidates.length
452
+ ? encodeCursor({
453
+ v: CURSOR_VERSION,
454
+ f: fingerprint,
455
+ sources: openStates.map(state => ({ path: state.relative, limit: state.limit, offset: state.offset })),
456
+ })
457
+ : null;
458
+ return {
459
+ entries,
460
+ nextCursor,
461
+ pageSize,
462
+ from: filters.from,
463
+ to: filters.to,
464
+ counts: this.countLevels(entries),
465
+ };
466
+ } finally {
467
+ for (const state of openStates) fs.closeSync(state.fd);
468
+ }
469
+ }
470
+
471
+ countLevels(entries) {
472
+ return Object.fromEntries(LOG_LEVELS.map(level => [level, entries.filter(entry => entry.level === level).length]));
473
+ }
474
+
475
+ exportToFile(filePath, filters = {}) {
476
+ let cursor = '';
477
+ let count = 0;
478
+ const secrets = this.currentSecrets();
479
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
480
+ const fd = fs.openSync(filePath, 'w', 0o600);
481
+ try {
482
+ do {
483
+ const page = this.query({ ...filters, cursor, pageSize: 1000 });
484
+ for (const entry of page.entries) {
485
+ fs.writeSync(fd, `${JSON.stringify(redactValue(entry, { secrets }))}\n`, null, 'utf8');
486
+ count += 1;
487
+ }
488
+ cursor = page.nextCursor || '';
489
+ } while (cursor);
490
+ fs.fsyncSync(fd);
491
+ } finally {
492
+ fs.closeSync(fd);
493
+ }
494
+ return { filePath, count };
495
+ }
496
+
497
+ findOrphanedOperations(filters = {}) {
498
+ const starts = new Map();
499
+ const completed = new Set();
500
+ let cursor = '';
501
+ let inspected = 0;
502
+ const maxEntries = Math.max(1, Math.min(Number(filters.maxEntries || 10000), 50000));
503
+ do {
504
+ const page = this.query({ ...filters, cursor, pageSize: Math.min(1000, maxEntries - inspected) });
505
+ for (const entry of page.entries) {
506
+ inspected += 1;
507
+ if (!entry.operationId) continue;
508
+ if (/\.started$/.test(entry.event)) starts.set(entry.operationId, entry);
509
+ if (TERMINAL_EVENTS.test(entry.event)) completed.add(entry.operationId);
510
+ }
511
+ cursor = inspected < maxEntries ? (page.nextCursor || '') : '';
512
+ } while (cursor);
513
+ return [...starts.entries()].filter(([operationId]) => !completed.has(operationId)).map(([, entry]) => entry);
514
+ }
515
+ }
516
+
517
+ function appendLog(configPath, appRoot, entry) {
518
+ const config = readConfig(configPath, appRoot);
519
+ const level = LEVELS.has(entry.level) ? entry.level : 'info';
520
+ if (!config.levels.includes(level)) return null;
521
+ const record = normalizeRecord({
522
+ ...entry,
523
+ level,
524
+ component: entry.component || entry.source || 'server',
525
+ context: entry.context || entry.meta || {},
526
+ });
527
+ const file = appendRecordSync(path.join(config.rootPath, 'system'), record);
528
+ return { file, record };
529
+ }
530
+
531
+ function readLogs(configPath, appRoot, filters = {}) {
532
+ const layout = new StorageLayout({ dataDir: appRoot });
533
+ const repository = new LogRepository({ layout });
534
+ const result = repository.query({
535
+ from: filters.from || filters.dateFrom || '',
536
+ to: filters.to || filters.dateTo || '',
537
+ levels: filters.levels || (filters.level && filters.level !== 'all' ? [filters.level] : []),
538
+ scope: filters.scope || '',
539
+ projectId: filters.projectId || '',
540
+ component: filters.component || (filters.source && filters.source !== 'all' ? filters.source : ''),
541
+ event: filters.event || '',
542
+ commitSha: filters.commitSha || '',
543
+ operationId: filters.operationId || '',
544
+ q: filters.q || '',
545
+ pageSize: filters.pageSize || filters.limit || DEFAULT_PAGE_SIZE,
546
+ cursor: filters.cursor || '',
547
+ });
548
+ if (filters.returnPage) return result;
549
+ if (filters.projectSlug && filters.projectSlug !== 'all') return result.entries.filter(entry => entry.projectSlug === filters.projectSlug);
550
+ return result.entries;
551
+ }
552
+
553
+ module.exports = {
554
+ SCHEMA,
555
+ LEVELS,
556
+ DEFAULT_PAGE_SIZE,
557
+ MAX_PAGE_SIZE,
558
+ Logger,
559
+ LogRepository,
560
+ defaultConfig,
561
+ normalizeConfig,
562
+ readConfig,
563
+ writeConfig,
564
+ appendLog,
565
+ readLogs,
566
+ normalizeRecord,
567
+ appendRecordSync,
568
+ redactString,
569
+ redactValue,
570
+ serializeError,
571
+ parseLine,
572
+ localDay,
573
+ readPreviousLine,
574
+ };