@agy-daddy/plugin-context 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antigravity Context Viewer Contributors
4
+ Copyright (c) 2026 Agy-Daddy Contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ Agy-Daddy Context Plugin (@agy-daddy/plugin-context)
2
+
3
+ This project incorporates context window analysis, error classification,
4
+ pulse capsule telemetry, and attachment inventory auditing derived from:
5
+ - iamvicliu/antigravity-suite (baseline commit c349284: meter-core.js,
6
+ pulse-capsule-overlay.js, attachment_scan.py, src/renderer/main.js)
7
+ Copyright (c) 2026 Antigravity Context Viewer Contributors (MIT License)
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @agy-daddy/plugin-context
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Agy-Daddy Layer-2 官方插件:顶栏上下文圆环与测速、详情与附件审计浮窗、底部 Pulse 实时能量胶囊。
4
+
5
+ ## 提供能力
6
+ - 服务:`context`(Node 域:`getSnapshot`、`rescan`、`getRecentCalls`、`auditAttachments`、`getMobileSnapshot`)与 `context-ui`(主世界域)
7
+ - 事件:`telemetry:generator-calls@1`(按 `callId` 去重供 `usage` 等消费者入账与延迟补拉)
8
+ - 状态:`state:context.snapshot@1`
9
+ - 可选消费:`usage.estimateCallsCost()`(未安装 `usage` 时安全降级)
10
+
11
+ ## 测试
12
+ ```sh
13
+ npm test
14
+ ```
@@ -0,0 +1,59 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "agy-daddy.context",
4
+ "publisher": "agy-daddy",
5
+ "version": "1.1.0",
6
+ "license": "MIT",
7
+ "displayName": {
8
+ "zh-CN": "上下文与实时速度",
9
+ "en": "Context & Live Speed"
10
+ },
11
+ "description": {
12
+ "zh-CN": "当前对话实时状态面板与单点胶囊(上下文窗口、本对话累计 Token 与实时生成速度,顶栏或输入框下方二选一)",
13
+ "en": "Real-time current conversation monitor (context window, session tokens, live tok/s speed) with exclusive composer or topbar placement"
14
+ },
15
+ "engines": {
16
+ "agyDaddy": "^1.0.0",
17
+ "antigravity": ">=2.32.0"
18
+ },
19
+ "main": "./src/node.js",
20
+ "renderer": "./src/renderer.js",
21
+ "world": "isolated",
22
+ "activationEvents": ["onStartup"],
23
+ "requires": {
24
+ "anchors": ["topbar.rightCluster", "composer.root"]
25
+ },
26
+ "provides": {
27
+ "services": {
28
+ "context": { "version": "1.0.0", "realm": "node" },
29
+ "context-ui": { "version": "1.0.0", "realm": "page-isolated" }
30
+ },
31
+ "events": ["telemetry:generator-calls@1", "context:auto-compact-triggered@1"],
32
+ "states": ["state:context.snapshot@1"]
33
+ },
34
+ "consumes": {
35
+ "usage": { "version": "^1.0.0", "optional": true }
36
+ },
37
+ "permissions": [
38
+ "dom:read",
39
+ "dom:write",
40
+ "rpc:read",
41
+ "fs:brain-read",
42
+ "bridge:route",
43
+ "native:install"
44
+ ],
45
+ "contributes": {
46
+ "topbar.units": [{ "id": "ring", "order": 10 }],
47
+ "topbar.popovers": [{ "id": "context-panel", "anchorId": "ring" }],
48
+ "settings": { "schema": "./settings.schema.json" },
49
+ "remote.panels": [{ "id": "context", "service": "context" }],
50
+ "commands": [
51
+ { "id": "context.rescan", "title": { "zh-CN": "重新扫描会话", "en": "Rescan session" } }
52
+ ],
53
+ "native": {
54
+ "mcp": "./native/mcp.json",
55
+ "skills": ["./native/skills"]
56
+ },
57
+ "locales": "./locales"
58
+ }
59
+ }
package/baseline.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "source": "iamvicliu/antigravity-suite",
3
+ "absorbedSha": "c349284",
4
+ "paths": [
5
+ "meter-core.js",
6
+ "pulse-capsule-overlay.js",
7
+ "attachment_scan.py",
8
+ "src/renderer/main.js"
9
+ ]
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "panel.title": "Current Conversation Monitor",
3
+ "panel.rescan": "Rescan",
4
+ "panel.noSession": "No active session",
5
+ "pulse.waiting": "Ctx -- · Session --",
6
+ "alert.warn240k": "Consider compacting (>240K cache degradation risk)",
7
+ "alert.cliff328k": "High cliff zone (>=328K cache miss risk)",
8
+ "alert.cacheDrop": "Context cache drop detected",
9
+ "alert.compressed": "Auto-compaction detected"
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "panel.title": "当前对话实时状态",
3
+ "panel.rescan": "重新扫描",
4
+ "panel.noSession": "暂无活跃会话",
5
+ "pulse.waiting": "窗口 -- · 本对话 --",
6
+ "alert.warn240k": "建议压缩上下文(>240K 缓存效率下降风险)",
7
+ "alert.cliff328k": "高风险断崖区(>=328K 易丢缓存)",
8
+ "alert.cacheDrop": "检测到上下文缓存失效",
9
+ "alert.compressed": "已触发自动压缩"
10
+ }
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ function readContextState(dataDir) {
8
+ const dir = dataDir || process.env.AGY_DADDY_PLUGIN_DATA_DIR || '';
9
+ const snapPath = dir ? path.join(dir, 'latest-snapshot.json') : '';
10
+ if (snapPath && fs.existsSync(snapPath)) {
11
+ try {
12
+ const parsed = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
13
+ return { ok: true, available: true, source: 'snapshot-file', ...parsed };
14
+ } catch {}
15
+ }
16
+ return {
17
+ ok: true,
18
+ available: false,
19
+ reason: 'NO_SNAPSHOT_YET',
20
+ used: null,
21
+ budget: null,
22
+ percent: null,
23
+ alerts: []
24
+ };
25
+ }
26
+
27
+ function handleRpcMessage(msg, dataDir) {
28
+ if (!msg || typeof msg !== 'object') return null;
29
+ if (msg.method === 'notifications/initialized') return null;
30
+
31
+ if (msg.method === 'initialize') {
32
+ return {
33
+ jsonrpc: '2.0',
34
+ id: msg.id ?? null,
35
+ result: {
36
+ protocolVersion: '2024-11-05',
37
+ capabilities: { tools: {} },
38
+ serverInfo: { name: 'agy-daddy-context-mcp', version: '1.0.0' }
39
+ }
40
+ };
41
+ }
42
+
43
+ if (msg.method === 'tools/list') {
44
+ return {
45
+ jsonrpc: '2.0',
46
+ id: msg.id ?? null,
47
+ result: {
48
+ tools: [
49
+ {
50
+ name: 'context_status',
51
+ description: 'Inspect current Antigravity session context window usage, cache hit rate, and 240K/328K cliff alerts.',
52
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false }
53
+ }
54
+ ]
55
+ }
56
+ };
57
+ }
58
+
59
+ if (msg.method === 'tools/call') {
60
+ const toolName = msg.params?.name;
61
+ if (toolName !== 'context_status') {
62
+ return {
63
+ jsonrpc: '2.0',
64
+ id: msg.id ?? null,
65
+ error: { code: -32601, message: `Unknown tool: ${toolName}` }
66
+ };
67
+ }
68
+ const status = readContextState(dataDir);
69
+ return {
70
+ jsonrpc: '2.0',
71
+ id: msg.id ?? null,
72
+ result: {
73
+ content: [{ type: 'text', text: JSON.stringify(status, null, 2) }],
74
+ structuredContent: status
75
+ }
76
+ };
77
+ }
78
+
79
+ if (msg.id !== undefined) {
80
+ return {
81
+ jsonrpc: '2.0',
82
+ id: msg.id,
83
+ error: { code: -32601, message: `Method not found: ${msg.method}` }
84
+ };
85
+ }
86
+ return null;
87
+ }
88
+
89
+ function startStdioServer(dataDir) {
90
+ let buf = Buffer.alloc(0);
91
+ let useContentLength = false;
92
+
93
+ const sendReply = (obj) => {
94
+ if (!obj) return;
95
+ const json = JSON.stringify(obj);
96
+ if (useContentLength) {
97
+ const byteLen = Buffer.byteLength(json, 'utf8');
98
+ process.stdout.write(`Content-Length: ${byteLen}\r\n\r\n${json}`);
99
+ } else {
100
+ process.stdout.write(`${json}\n`);
101
+ }
102
+ };
103
+
104
+ process.stdin.on('data', (chunk) => {
105
+ buf = Buffer.concat([buf, chunk]);
106
+ while (buf.length > 0) {
107
+ const str = buf.toString('utf8');
108
+ if (/^Content-Length:\s*(\d+)/i.test(str)) {
109
+ useContentLength = true;
110
+ const headerEnd = buf.indexOf('\r\n\r\n');
111
+ const altEnd = headerEnd < 0 ? buf.indexOf('\n\n') : -1;
112
+ const sepIdx = headerEnd >= 0 ? headerEnd : altEnd;
113
+ const sepLen = headerEnd >= 0 ? 4 : 2;
114
+ if (sepIdx < 0) return;
115
+ const headerText = buf.subarray(0, sepIdx).toString('utf8');
116
+ const m = headerText.match(/Content-Length:\s*(\d+)/i);
117
+ const bodyLen = m ? Number(m[1]) : 0;
118
+ const totalNeed = sepIdx + sepLen + bodyLen;
119
+ if (buf.length < totalNeed) return;
120
+ const bodyRaw = buf.subarray(sepIdx + sepLen, totalNeed).toString('utf8');
121
+ buf = buf.subarray(totalNeed);
122
+ try { sendReply(handleRpcMessage(JSON.parse(bodyRaw), dataDir)); } catch {}
123
+ continue;
124
+ }
125
+ const nlIdx = buf.indexOf(10);
126
+ if (nlIdx < 0) return;
127
+ const line = buf.subarray(0, nlIdx).toString('utf8').trim();
128
+ buf = buf.subarray(nlIdx + 1);
129
+ if (!line) continue;
130
+ try { sendReply(handleRpcMessage(JSON.parse(line), dataDir)); } catch {}
131
+ }
132
+ });
133
+ process.stdin.on('end', () => process.exit(0));
134
+ }
135
+
136
+ if (require.main === module) {
137
+ startStdioServer(process.env.AGY_DADDY_PLUGIN_DATA_DIR || '');
138
+ }
139
+
140
+ module.exports = { readContextState, handleRpcMessage, startStdioServer };
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "agy-daddy-context": {
4
+ "command": "node",
5
+ "args": ["./native/mcp-server.js"]
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: context-governance
3
+ description: Monitor Antigravity session context usage via `context_status`, guard against 240K/328K prompt-cache cliffs, and recommend `/compact` before heavy full-context recomputation stalls.
4
+ ---
5
+
6
+ # Context Governance
7
+
8
+ 1. Call MCP tool `context_status` before starting large multi-file refactors in an already long session.
9
+ 2. When `used >= 240000` or `cacheDropDetected === true`, finish the current atomic verification step cleanly and advise running `/compact`.
10
+ 3. Do not dump large source files blindly; read bounded line ranges (`<= 150` lines) to keep cache footprint compact.
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@agy-daddy/plugin-context",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Agy-Daddy context ring, audit panel, attachment inspector, and composer pulse capsule plugin",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/agy-daddy/agy-daddy.git",
9
+ "directory": "agy-daddy-plugin-context"
10
+ },
11
+ "main": "./src/node.js",
12
+ "agyPlugin": "./agy-plugin.json",
13
+ "files": [
14
+ "agy-plugin.json",
15
+ "settings.schema.json",
16
+ "src/",
17
+ "locales/",
18
+ "native/",
19
+ "baseline.json",
20
+ "README.md",
21
+ "LICENSE",
22
+ "NOTICE"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "test": "node -e \"const cp=require('node:child_process'),fs=require('node:fs'),p=require('node:path');const files=fs.readdirSync('test').filter(f=>f.endsWith('.test.js')).sort().map(f=>p.join('test',f));process.exit(cp.spawnSync(process.execPath,['--test',...files],{stdio:'inherit',env:{...process.env,AGY_DADDY_TEST_MODE:'1'}}).status??1)\""
29
+ },
30
+ "engines": {
31
+ "node": ">=22.4.0"
32
+ }
33
+ }
@@ -0,0 +1,84 @@
1
+ {
2
+ "title": { "zh-CN": "上下文与实时速度", "en": "Context & Live Speed" },
3
+ "fields": [
4
+ {
5
+ "key": "displayLocation",
6
+ "type": "enum",
7
+ "default": "composer",
8
+ "options": [
9
+ { "value": "composer", "label": "输入框下方" },
10
+ { "value": "topbar", "label": "顶栏" }
11
+ ],
12
+ "group": { "zh-CN": "显示位置与采样", "en": "Display & Sampling" },
13
+ "label": { "zh-CN": "胶囊显示位置", "en": "Capsule position" },
14
+ "description": { "zh-CN": "二选一:仅在输入框下方或仅在顶栏显示实时胶囊,点击就近弹出详情面板", "en": "Exclusive choice: show live capsule below the composer or in the topbar, opening the panel nearby on click" }
15
+ },
16
+ {
17
+ "key": "showSpeed",
18
+ "type": "boolean",
19
+ "default": true,
20
+ "group": { "zh-CN": "显示位置与采样", "en": "Display & Sampling" },
21
+ "label": { "zh-CN": "显示生成速度", "en": "Show generation speed" },
22
+ "description": { "zh-CN": "在胶囊中实时显示流式估算速率 (~tok/s) 及完成后的精确速率", "en": "Show live estimated streaming rate (~tok/s) and final exact rate in the capsule" }
23
+ },
24
+ {
25
+ "key": "pollIntervalMs",
26
+ "type": "number",
27
+ "min": 1000,
28
+ "max": 30000,
29
+ "default": 3000,
30
+ "group": { "zh-CN": "显示位置与采样", "en": "Display & Sampling" },
31
+ "unit": { "zh-CN": "毫秒", "en": "ms" },
32
+ "placeholder": "3000",
33
+ "label": { "zh-CN": "轮询采样间隔", "en": "Polling interval" },
34
+ "description": { "zh-CN": "定期读取当前会话记录并重算 Token 构成的时间间隔", "en": "Interval between transcript scans to recompute token breakdown" }
35
+ },
36
+ {
37
+ "key": "warnThreshold",
38
+ "type": "string",
39
+ "default": "240K",
40
+ "group": { "zh-CN": "缓存断崖与压缩", "en": "Cache Cliff & Compaction" },
41
+ "placeholder": "240K 或 50%",
42
+ "label": { "zh-CN": "预警阈值", "en": "Warning threshold" },
43
+ "description": { "zh-CN": "支持绝对值(如 240K / 240000)或窗口百分比(如 50%);达到后胶囊变橙提醒", "en": "Supports absolute tokens (e.g. 240K / 240000) or window percentage (e.g. 50%)" }
44
+ },
45
+ {
46
+ "key": "cliffThreshold",
47
+ "type": "string",
48
+ "default": "328K",
49
+ "group": { "zh-CN": "缓存断崖与压缩", "en": "Cache Cliff & Compaction" },
50
+ "placeholder": "328K 或 70%",
51
+ "label": { "zh-CN": "断崖阈值", "en": "Critical cliff threshold" },
52
+ "description": { "zh-CN": "支持绝对值(如 328K / 328000)或窗口百分比(如 70%);达到后标记高风险断崖", "en": "Supports absolute tokens (e.g. 328K / 328000) or window percentage (e.g. 70%)" }
53
+ },
54
+ {
55
+ "key": "compactPolicy",
56
+ "type": "enum",
57
+ "default": "remind",
58
+ "options": [
59
+ { "value": "remind", "label": "仅提醒" },
60
+ { "value": "idle_prompt", "label": "仅预警快捷按钮" },
61
+ { "value": "cliff_auto", "label": "仅断崖自动压缩" },
62
+ { "value": "idle_and_cliff", "label": "预警快捷按钮 + 断崖自动压缩" }
63
+ ],
64
+ "group": { "zh-CN": "缓存断崖与压缩", "en": "Cache Cliff & Compaction" },
65
+ "label": { "zh-CN": "压缩触发策略", "en": "Compaction policy" },
66
+ "description": { "zh-CN": "支持四档自由组合:仅提醒;仅开 A(达预警且空闲无草稿时在胶囊旁显示一键压缩);仅开 B(达断崖等本步结束自动发 /compact,不强杀生成中回复);A+B 同时开启", "en": "Supports all 4 combinations: remind only; A only (quick compact button when warn & idle & empty); B only (auto-send /compact after turn finishes at cliff); or A+B combined" }
67
+ },
68
+ {
69
+ "key": "autoCompactOnCacheDrop",
70
+ "type": "boolean",
71
+ "default": false,
72
+ "group": { "zh-CN": "缓存断崖与压缩", "en": "Cache Cliff & Compaction" },
73
+ "label": { "zh-CN": "丢缓存强行触发压缩", "en": "Force compact on cache drop" },
74
+ "description": { "zh-CN": "独立开关,默认关闭;开启后检测到缓存失效时无视上方策略与阈值,等本步结束立即自动发 /compact(发前暂存并恢复草稿)", "en": "Independent override (default OFF); ignores policy & thresholds when cache drop is detected and auto-sends /compact once idle" }
75
+ }
76
+ ],
77
+ "actions": [
78
+ {
79
+ "id": "rescan",
80
+ "command": "context.rescan",
81
+ "label": { "zh-CN": "立即重新扫描会话", "en": "Rescan Session Now" }
82
+ }
83
+ ]
84
+ }
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { measure } = require('./context-analyzer');
6
+
7
+ const DEFAULT_MAX_FILE_BYTES = 16 * 1024 * 1024;
8
+ const TEXT_MIME_PREFIXES = ['text/', 'application/json', 'application/xml', 'application/javascript', 'application/typescript', 'application/x-yaml', 'application/csv'];
9
+ const TEXT_EXTENSIONS = new Set([
10
+ '.txt', '.md', '.markdown', '.json', '.jsonl', '.yaml', '.yml', '.csv', '.tsv',
11
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.py', '.go', '.rs', '.java',
12
+ '.c', '.cc', '.cpp', '.h', '.hpp', '.css', '.scss', '.html', '.xml', '.svg',
13
+ '.sql', '.sh', '.zsh', '.bash', '.toml', '.ini', '.conf', '.log'
14
+ ]);
15
+
16
+ function uriToLocalPath(uri) {
17
+ if (!uri || typeof uri !== 'string') return null;
18
+ if (uri.startsWith('inline:')) return null;
19
+ if (/^file:\/\//i.test(uri)) {
20
+ if (/^file:\/\/\/?[A-Za-z]:[\\/]/i.test(uri)) {
21
+ const stripped = uri.replace(/^file:\/\/\/?/i, '');
22
+ try {
23
+ return decodeURIComponent(stripped);
24
+ } catch {
25
+ return stripped;
26
+ }
27
+ }
28
+ try {
29
+ return decodeURIComponent(new URL(uri).pathname);
30
+ } catch {
31
+ return uri.slice('file://'.length);
32
+ }
33
+ }
34
+ if (path.isAbsolute(uri)) return uri;
35
+ return null;
36
+ }
37
+
38
+ function isReadableTextFile(filePath, mime) {
39
+ const cleanMime = String(mime || '').toLowerCase();
40
+ if (cleanMime && TEXT_MIME_PREFIXES.some((p) => cleanMime.startsWith(p))) return true;
41
+ const ext = path.extname(String(filePath || '')).toLowerCase();
42
+ return TEXT_EXTENSIONS.has(ext);
43
+ }
44
+
45
+ /**
46
+ * 只读审计附件目录与引用体量,绝不返回原始文本内容
47
+ */
48
+ function auditAttachments(mediaList = [], options = {}) {
49
+ const maxFileBytes = Number(options.maxFileBytes) > 0 ? Number(options.maxFileBytes) : DEFAULT_MAX_FILE_BYTES;
50
+ const list = Array.isArray(mediaList) ? mediaList : [];
51
+ const items = [];
52
+ const totals = {
53
+ count: 0,
54
+ userCount: 0,
55
+ assistantCount: 0,
56
+ measuredCount: 0,
57
+ unknownCount: 0,
58
+ chars: 0,
59
+ bytes: 0,
60
+ low: 0,
61
+ high: 0
62
+ };
63
+
64
+ for (const raw of list) {
65
+ if (!raw || typeof raw !== 'object') continue;
66
+ const source = raw.source === 'user' ? 'user' : 'assistant';
67
+ const localPath = uriToLocalPath(raw.uri);
68
+ totals.count++;
69
+ if (source === 'user') totals.userCount++;
70
+ else totals.assistantCount++;
71
+
72
+ if (!localPath || !fs.existsSync(localPath)) {
73
+ totals.unknownCount++;
74
+ items.push({
75
+ name: raw.name || 'unknown',
76
+ mime: raw.mime || '',
77
+ source,
78
+ references: Number(raw.references || 1),
79
+ status: raw.uri?.startsWith('inline:') ? 'inline_unmeasured' : 'missing',
80
+ chars: 0,
81
+ bytes: 0,
82
+ low: 0,
83
+ high: 0
84
+ });
85
+ continue;
86
+ }
87
+
88
+ let stat;
89
+ try {
90
+ stat = fs.statSync(localPath);
91
+ } catch {
92
+ totals.unknownCount++;
93
+ items.push({
94
+ name: raw.name || path.basename(localPath),
95
+ mime: raw.mime || '',
96
+ source,
97
+ references: Number(raw.references || 1),
98
+ status: 'unreadable',
99
+ chars: 0,
100
+ bytes: 0,
101
+ low: 0,
102
+ high: 0
103
+ });
104
+ continue;
105
+ }
106
+
107
+ if (!stat.isFile() || stat.size > maxFileBytes || !isReadableTextFile(localPath, raw.mime)) {
108
+ totals.unknownCount++;
109
+ totals.bytes += stat.isFile() ? stat.size : 0;
110
+ items.push({
111
+ name: raw.name || path.basename(localPath),
112
+ mime: raw.mime || '',
113
+ source,
114
+ references: Number(raw.references || 1),
115
+ status: stat.size > maxFileBytes ? 'oversized' : 'binary_or_unparsed',
116
+ chars: 0,
117
+ bytes: stat.size,
118
+ low: 0,
119
+ high: 0
120
+ });
121
+ continue;
122
+ }
123
+
124
+ let text = '';
125
+ try {
126
+ text = fs.readFileSync(localPath, 'utf8');
127
+ } catch {
128
+ totals.unknownCount++;
129
+ items.push({
130
+ name: raw.name || path.basename(localPath),
131
+ mime: raw.mime || '',
132
+ source,
133
+ references: Number(raw.references || 1),
134
+ status: 'read_error',
135
+ chars: 0,
136
+ bytes: stat.size,
137
+ low: 0,
138
+ high: 0
139
+ });
140
+ continue;
141
+ }
142
+
143
+ const est = measure(text);
144
+ totals.measuredCount++;
145
+ totals.chars += est.chars;
146
+ totals.bytes += est.bytes;
147
+ totals.low += est.low;
148
+ totals.high += est.high;
149
+
150
+ items.push({
151
+ name: raw.name || path.basename(localPath),
152
+ mime: raw.mime || '',
153
+ source,
154
+ references: Number(raw.references || 1),
155
+ status: 'measured',
156
+ chars: est.chars,
157
+ bytes: est.bytes,
158
+ low: est.low,
159
+ high: est.high
160
+ });
161
+ }
162
+
163
+ return { items, totals };
164
+ }
165
+
166
+ module.exports = {
167
+ DEFAULT_MAX_FILE_BYTES,
168
+ uriToLocalPath,
169
+ isReadableTextFile,
170
+ auditAttachments
171
+ };