@oaksecurity/aitm 0.0.0-stage → 2.3.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/.env.example +11 -0
- package/CHANGELOG.md +100 -0
- package/LICENSE +21 -0
- package/README.md +229 -2
- package/SECURITY.md +49 -0
- package/SPEC.md +304 -0
- package/docs/api.md +332 -0
- package/docs/inputs-and-limits.md +78 -0
- package/docs/usage.md +351 -0
- package/examples/custody-architecture.md +27 -0
- package/package.json +67 -4
- package/src/api/server.js +591 -0
- package/src/api/web.js +38 -0
- package/src/application.js +32 -0
- package/src/assessments.js +37 -0
- package/src/assets/BDOGrotesk-Bold.ttf +0 -0
- package/src/assets/BDOGrotesk-Regular.ttf +0 -0
- package/src/assets/OFL.txt +93 -0
- package/src/assets/README.md +10 -0
- package/src/cli.js +224 -0
- package/src/client.js +88 -0
- package/src/config.js +105 -0
- package/src/doctor.js +128 -0
- package/src/engine/credentials.js +31 -0
- package/src/engine/download.js +135 -0
- package/src/engine/engine.js +783 -0
- package/src/engine/errors.js +23 -0
- package/src/engine/generation.js +121 -0
- package/src/engine/ingest.js +444 -0
- package/src/engine/pdf-layout.js +204 -0
- package/src/engine/pdf-report.js +573 -0
- package/src/engine/prompts.js +82 -0
- package/src/engine/providers.js +476 -0
- package/src/engine/references.js +112 -0
- package/src/engine/report.js +200 -0
- package/src/engine/schema.js +267 -0
- package/src/engine/store.js +115 -0
- package/src/engine/validate.js +397 -0
- package/src/engine/zip.js +70 -0
- package/src/index.js +5 -0
- package/src/source-input.js +32 -0
- package/src/token.js +59 -0
- package/src/tui/app.js +694 -0
- package/src/tui/editor.js +34 -0
- package/src/tui/file-picker.js +111 -0
- package/src/tui/logo.js +8 -0
- package/src/tui/progress.js +90 -0
- package/src/tui/report-reader.js +105 -0
- package/src/tui/select.js +63 -0
- package/src/tui/workbench.js +377 -0
- package/src/version.js +5 -0
- package/src/web/app.js +729 -0
- package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
- package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
- package/src/web/assets/README.md +5 -0
- package/src/web/assets/aitm-mark.svg +12 -0
- package/src/web/assets/oak-white.svg +166 -0
- package/src/web/html.js +32 -0
- package/src/web/index.html +26 -0
- package/src/web/markdown.js +48 -0
- package/src/web/styles.css +1450 -0
- package/src/web/views.js +254 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export class AppError extends Error {
|
|
2
|
+
constructor(status, code, message) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.status = status;
|
|
5
|
+
this.code = code;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function insist(condition, message, status = 422, code = 'invalid_input') {
|
|
10
|
+
if (!condition) throw new AppError(status, code, message);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function parse(schema, value) {
|
|
14
|
+
const result = schema.safeParse(value);
|
|
15
|
+
if (!result.success) {
|
|
16
|
+
const detail = result.error.issues
|
|
17
|
+
.slice(0, 6)
|
|
18
|
+
.map((i) => `${i.path.join('.') || 'input'}: ${i.message}`)
|
|
19
|
+
.join('; ');
|
|
20
|
+
throw new AppError(422, 'invalid_input', detail);
|
|
21
|
+
}
|
|
22
|
+
return result.data;
|
|
23
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { Schemas, enabledPhases } from './schema.js';
|
|
3
|
+
import { sourceBatches } from './ingest.js';
|
|
4
|
+
import { modelItems, rankedThreats } from './validate.js';
|
|
5
|
+
|
|
6
|
+
export function generationSources(phase, project) {
|
|
7
|
+
if (phase === 'model') return sourceBatches(project);
|
|
8
|
+
return [
|
|
9
|
+
project.sources.flatMap((source) =>
|
|
10
|
+
source.files.map((file) => ({
|
|
11
|
+
id: file.id,
|
|
12
|
+
path: file.path,
|
|
13
|
+
source: source.label,
|
|
14
|
+
sourceId: source.id,
|
|
15
|
+
hash: file.hash,
|
|
16
|
+
lines: file.lines,
|
|
17
|
+
characters: file.text.length,
|
|
18
|
+
})),
|
|
19
|
+
),
|
|
20
|
+
];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Each phase consumes its immediate domain inputs, rather than every historical
|
|
24
|
+
// representation of the same objects. Classification IDs are not model IDs.
|
|
25
|
+
export function generationArtifacts(phase, project) {
|
|
26
|
+
const inputs =
|
|
27
|
+
{
|
|
28
|
+
ingest: [],
|
|
29
|
+
model: ['ingest'],
|
|
30
|
+
stride: ['model'],
|
|
31
|
+
trees: ['model', 'stride'],
|
|
32
|
+
coordination: ['model', 'stride'],
|
|
33
|
+
report: ['model', 'stride', 'trees', 'coordination'],
|
|
34
|
+
}[phase] || [];
|
|
35
|
+
const enabled = new Set(enabledPhases(project).map((p) => p.id));
|
|
36
|
+
return Object.fromEntries(
|
|
37
|
+
inputs
|
|
38
|
+
.filter((id) => enabled.has(id) && project.artifacts[id])
|
|
39
|
+
.map((id) => [id, project.artifacts[id].data]),
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Constrain cross-phase links at generation time, as well as validating them
|
|
44
|
+
// afterwards. A provider cannot substitute an old candidate ID for a model ID.
|
|
45
|
+
export function generationSchema(phase, project) {
|
|
46
|
+
const schema = Schemas[phase];
|
|
47
|
+
const model = project.artifacts.model?.data;
|
|
48
|
+
const refs = (items, minimum = 0) => {
|
|
49
|
+
const values = [...new Set(items.map((item) => item.id))];
|
|
50
|
+
return values.length
|
|
51
|
+
? z.array(z.enum(values)).min(minimum).max(200)
|
|
52
|
+
: z.array(z.string()).max(0);
|
|
53
|
+
};
|
|
54
|
+
if (phase === 'ingest') return schema.extend({ candidates: schema.shape.candidates.max(0) });
|
|
55
|
+
if (phase === 'model')
|
|
56
|
+
return schema.extend({
|
|
57
|
+
protectedAssets: z.array(schema.shape.protectedAssets.element).max(100),
|
|
58
|
+
invariants: z.array(schema.shape.invariants.element).max(100),
|
|
59
|
+
components: z.array(schema.shape.components.element).max(100),
|
|
60
|
+
});
|
|
61
|
+
if (phase === 'stride' && model)
|
|
62
|
+
return schema.extend({
|
|
63
|
+
threats: z
|
|
64
|
+
.array(
|
|
65
|
+
schema.shape.threats.element.extend({
|
|
66
|
+
targetIds: refs([...model.components, ...model.roles, ...model.edges], 1),
|
|
67
|
+
actorIds: refs(model.threatActors),
|
|
68
|
+
assetIds: refs(model.protectedAssets),
|
|
69
|
+
invariantIds: refs(model.invariants),
|
|
70
|
+
}),
|
|
71
|
+
)
|
|
72
|
+
.max(120),
|
|
73
|
+
coverage: schema.shape.coverage.max(0),
|
|
74
|
+
});
|
|
75
|
+
if (phase === 'trees') {
|
|
76
|
+
const threatIds = rankedThreats(project)
|
|
77
|
+
.slice(0, project.config.treeLimit)
|
|
78
|
+
.map((t) => t.id);
|
|
79
|
+
if (!threatIds.length)
|
|
80
|
+
return schema.extend({
|
|
81
|
+
trees: schema.shape.trees.max(0),
|
|
82
|
+
omitted: schema.shape.omitted.max(0),
|
|
83
|
+
});
|
|
84
|
+
return schema.extend({
|
|
85
|
+
trees: z.array(schema.shape.trees.element.extend({ threatId: z.enum(threatIds) })).max(10),
|
|
86
|
+
omitted: z
|
|
87
|
+
.array(schema.shape.omitted.element.extend({ threatId: z.enum(threatIds) }))
|
|
88
|
+
.max(120),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
if (phase === 'coordination' && model)
|
|
92
|
+
return schema.extend({
|
|
93
|
+
scenarios: z
|
|
94
|
+
.array(
|
|
95
|
+
schema.shape.scenarios.element.extend({
|
|
96
|
+
actorIds: refs([...model.threatActors, ...model.roles], 1),
|
|
97
|
+
assetIds: refs(model.protectedAssets, 1),
|
|
98
|
+
}),
|
|
99
|
+
)
|
|
100
|
+
.max(60),
|
|
101
|
+
});
|
|
102
|
+
if (phase === 'report' && model)
|
|
103
|
+
return schema.extend({
|
|
104
|
+
roadmap: z
|
|
105
|
+
.array(
|
|
106
|
+
schema.shape.roadmap.element.extend({
|
|
107
|
+
linkedIds: refs(
|
|
108
|
+
[
|
|
109
|
+
...modelItems(model),
|
|
110
|
+
...(project.artifacts.stride?.data.threats || []),
|
|
111
|
+
...(project.artifacts.trees?.data.trees || []).flatMap((tree) => tree.nodes),
|
|
112
|
+
...(project.artifacts.coordination?.data.scenarios || []),
|
|
113
|
+
],
|
|
114
|
+
1,
|
|
115
|
+
),
|
|
116
|
+
}),
|
|
117
|
+
)
|
|
118
|
+
.max(100),
|
|
119
|
+
});
|
|
120
|
+
return schema;
|
|
121
|
+
}
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { promises as fs, constants } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import ignore from 'ignore';
|
|
8
|
+
import { insist, parse } from './errors.js';
|
|
9
|
+
import { SourceInput } from './schema.js';
|
|
10
|
+
import { downloadDocument } from './download.js';
|
|
11
|
+
import { readZip } from './zip.js';
|
|
12
|
+
|
|
13
|
+
const exec = promisify(execFile);
|
|
14
|
+
const SKIP = new Set([
|
|
15
|
+
'.git',
|
|
16
|
+
'node_modules',
|
|
17
|
+
'vendor',
|
|
18
|
+
'.venv',
|
|
19
|
+
'venv',
|
|
20
|
+
'dist',
|
|
21
|
+
'build',
|
|
22
|
+
'coverage',
|
|
23
|
+
'.next',
|
|
24
|
+
'.aitm',
|
|
25
|
+
'.ssh',
|
|
26
|
+
'.aws',
|
|
27
|
+
'.config',
|
|
28
|
+
]);
|
|
29
|
+
const SECRET =
|
|
30
|
+
/^(\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx)|(?:keys|credentials|secrets)(?:\..*)?|id_rsa|id_ed25519)$/i;
|
|
31
|
+
const BINARY =
|
|
32
|
+
/\.(?:png|jpe?g|gif|webp|ico|woff2?|ttf|otf|zip|gz|tgz|tar|7z|exe|dll|so|dylib|mp[34]|mov|docm|xlsm|doc|xlsx?|pptx?)$/i;
|
|
33
|
+
export const LIMITS = Object.freeze({
|
|
34
|
+
files: 1000,
|
|
35
|
+
projectFiles: 2000,
|
|
36
|
+
fileBytes: 8 * 1024 * 1024,
|
|
37
|
+
totalBytes: 32 * 1024 * 1024,
|
|
38
|
+
fileChars: 8 * 1024 * 1024,
|
|
39
|
+
sourceChars: 32 * 1024 * 1024,
|
|
40
|
+
projectChars: 32 * 1024 * 1024,
|
|
41
|
+
});
|
|
42
|
+
export const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
43
|
+
|
|
44
|
+
export function safePath(value) {
|
|
45
|
+
insist(
|
|
46
|
+
!value.includes('\\') &&
|
|
47
|
+
!value.includes('\0') &&
|
|
48
|
+
!value.includes(':') &&
|
|
49
|
+
!path.posix.isAbsolute(value),
|
|
50
|
+
'Use a relative file path.',
|
|
51
|
+
);
|
|
52
|
+
insist(
|
|
53
|
+
value.split('/').every((p) => p && p !== '.' && p !== '..'),
|
|
54
|
+
'File paths cannot contain empty segments, . or ...',
|
|
55
|
+
);
|
|
56
|
+
insist(
|
|
57
|
+
!value.split('/').some((p) => SKIP.has(p) || SECRET.test(p)),
|
|
58
|
+
'Credential and dependency paths cannot be ingested.',
|
|
59
|
+
);
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function validateDocx(buffer) {
|
|
64
|
+
// Read declared ZIP sizes before handing a document to the XML extractor.
|
|
65
|
+
const eocd = buffer.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
|
66
|
+
insist(eocd >= 0 && eocd + 22 <= buffer.length, 'Invalid DOCX archive.');
|
|
67
|
+
const count = buffer.readUInt16LE(eocd + 10);
|
|
68
|
+
let cursor = buffer.readUInt32LE(eocd + 16),
|
|
69
|
+
size = 0;
|
|
70
|
+
insist(count <= 2000, 'DOCX has too many archive entries.');
|
|
71
|
+
for (let i = 0; i < count; i++) {
|
|
72
|
+
insist(
|
|
73
|
+
cursor + 46 <= buffer.length && buffer.readUInt32LE(cursor) === 0x02014b50,
|
|
74
|
+
'Invalid DOCX directory.',
|
|
75
|
+
);
|
|
76
|
+
size += buffer.readUInt32LE(cursor + 24);
|
|
77
|
+
insist(size <= LIMITS.totalBytes, 'DOCX expands beyond the document size limit.');
|
|
78
|
+
cursor +=
|
|
79
|
+
46 +
|
|
80
|
+
buffer.readUInt16LE(cursor + 28) +
|
|
81
|
+
buffer.readUInt16LE(cursor + 30) +
|
|
82
|
+
buffer.readUInt16LE(cursor + 32);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function extract(name, buffer) {
|
|
87
|
+
insist(buffer.length <= LIMITS.fileBytes, 'File exceeds the 8 MiB limit.');
|
|
88
|
+
if (/\.pdf$/i.test(name)) {
|
|
89
|
+
const { PDFParse } = await import('pdf-parse');
|
|
90
|
+
const parser = new PDFParse({ data: buffer });
|
|
91
|
+
try {
|
|
92
|
+
return (await parser.getText()).text;
|
|
93
|
+
} finally {
|
|
94
|
+
await parser.destroy();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (/\.docx$/i.test(name)) {
|
|
98
|
+
validateDocx(buffer);
|
|
99
|
+
const mammoth = await import('mammoth');
|
|
100
|
+
return (await mammoth.default.extractRawText({ buffer })).value;
|
|
101
|
+
}
|
|
102
|
+
insist(
|
|
103
|
+
!BINARY.test(name) && !buffer.includes(0),
|
|
104
|
+
'Unsupported binary; use text, source code, PDF or DOCX.',
|
|
105
|
+
);
|
|
106
|
+
try {
|
|
107
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buffer);
|
|
108
|
+
} catch {
|
|
109
|
+
throw new Error('Text files must be UTF-8.');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function ingest(raw, { signal, sourceId = randomUUID(), gitRunner = exec } = {}) {
|
|
114
|
+
const input = parse(SourceInput, raw);
|
|
115
|
+
const files = [],
|
|
116
|
+
warnings = [];
|
|
117
|
+
let totalBytes = 0,
|
|
118
|
+
totalChars = 0,
|
|
119
|
+
temp = null,
|
|
120
|
+
commit = null,
|
|
121
|
+
locator = null;
|
|
122
|
+
const warn = (message) => {
|
|
123
|
+
if (warnings.length < 100) warnings.push(message);
|
|
124
|
+
};
|
|
125
|
+
async function add(name, buffer) {
|
|
126
|
+
signal?.throwIfAborted();
|
|
127
|
+
safePath(name);
|
|
128
|
+
totalBytes += buffer.length;
|
|
129
|
+
insist(
|
|
130
|
+
totalBytes <= LIMITS.totalBytes && files.length < LIMITS.files,
|
|
131
|
+
'Source exceeds the 32 MiB / 1000 file limit. Narrow the selected folder.',
|
|
132
|
+
);
|
|
133
|
+
const original = (await extract(name, buffer)).replace(/\r\n?/g, '\n');
|
|
134
|
+
if (!original.trim()) {
|
|
135
|
+
warn(`${name}: no extractable text (scanned documents require OCR).`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
insist(
|
|
139
|
+
original.length <= LIMITS.fileChars,
|
|
140
|
+
`${name}: extracted text exceeds 8 MiB. Split this document into smaller files.`,
|
|
141
|
+
);
|
|
142
|
+
insist(
|
|
143
|
+
totalChars + original.length <= LIMITS.sourceChars,
|
|
144
|
+
'Extracted source text exceeds 32 MiB. Narrow the selected source.',
|
|
145
|
+
);
|
|
146
|
+
const text = original;
|
|
147
|
+
totalChars += text.length;
|
|
148
|
+
if (text)
|
|
149
|
+
files.push({
|
|
150
|
+
id: `file-${hash(sourceId + ':' + name).slice(0, 20)}`,
|
|
151
|
+
path: name,
|
|
152
|
+
hash: hash(buffer),
|
|
153
|
+
bytes: buffer.length,
|
|
154
|
+
text,
|
|
155
|
+
lines: text.split('\n').length,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
async function archive(buffer, prefix = '') {
|
|
159
|
+
insist(buffer.length <= LIMITS.fileBytes, 'ZIP exceeds the 8 MiB upload limit.');
|
|
160
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'aitm-zip-'));
|
|
161
|
+
try {
|
|
162
|
+
await readZip(buffer, {
|
|
163
|
+
signal,
|
|
164
|
+
limits: LIMITS,
|
|
165
|
+
warn,
|
|
166
|
+
accept: (name) =>
|
|
167
|
+
!name
|
|
168
|
+
.split('/')
|
|
169
|
+
.some((part) => SKIP.has(part) || SECRET.test(part) || part === '__MACOSX') &&
|
|
170
|
+
!BINARY.test(name),
|
|
171
|
+
onFile: async (name, content) => {
|
|
172
|
+
const file = path.join(directory, prefix, name);
|
|
173
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
174
|
+
await fs.writeFile(file, content, { flag: 'wx', mode: 0o600 });
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
await walk(await fs.realpath(directory));
|
|
178
|
+
} finally {
|
|
179
|
+
await fs.rm(directory, { recursive: true, force: true });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function walk(root, relative = '', rules = []) {
|
|
183
|
+
signal?.throwIfAborted();
|
|
184
|
+
const dir = path.join(root, relative);
|
|
185
|
+
try {
|
|
186
|
+
const p = path.join(dir, '.gitignore');
|
|
187
|
+
const stat = await fs.lstat(p);
|
|
188
|
+
if (stat.isFile() && stat.size < 100000)
|
|
189
|
+
rules = [...rules, { base: relative, match: ignore().add(await fs.readFile(p, 'utf8')) }];
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (error.code !== 'ENOENT') throw error;
|
|
192
|
+
}
|
|
193
|
+
const entries = (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) =>
|
|
194
|
+
a.name.localeCompare(b.name),
|
|
195
|
+
);
|
|
196
|
+
// Read architecture evidence first; every accepted file is preserved in full.
|
|
197
|
+
entries.sort(
|
|
198
|
+
(a, b) =>
|
|
199
|
+
Number(/readme|spec|architect|whitepaper/i.test(b.name)) -
|
|
200
|
+
Number(/readme|spec|architect|whitepaper/i.test(a.name)),
|
|
201
|
+
);
|
|
202
|
+
for (const entry of entries) {
|
|
203
|
+
const name = relative ? `${relative}/${entry.name}` : entry.name;
|
|
204
|
+
if (SKIP.has(entry.name) || SECRET.test(entry.name)) continue;
|
|
205
|
+
if (entry.isSymbolicLink()) {
|
|
206
|
+
warn(`${name}: symlink skipped.`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
let ignored = false;
|
|
210
|
+
for (const rule of rules) {
|
|
211
|
+
const candidate =
|
|
212
|
+
name.slice(rule.base ? rule.base.length + 1 : 0) + (entry.isDirectory() ? '/' : '');
|
|
213
|
+
const result = rule.match.test(candidate);
|
|
214
|
+
if (result.ignored) ignored = true;
|
|
215
|
+
else if (result.unignored) ignored = false;
|
|
216
|
+
}
|
|
217
|
+
if (ignored) continue;
|
|
218
|
+
if (entry.isDirectory()) {
|
|
219
|
+
await walk(root, name, rules);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (!entry.isFile() || BINARY.test(entry.name)) continue;
|
|
223
|
+
const absolute = path.join(root, name);
|
|
224
|
+
const handle = await fs.open(absolute, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
225
|
+
try {
|
|
226
|
+
const stat = await handle.stat();
|
|
227
|
+
const real = await fs.realpath(absolute);
|
|
228
|
+
insist(real.startsWith(root + path.sep), 'Source changed outside the selected root.');
|
|
229
|
+
if (stat.size > LIMITS.fileBytes) {
|
|
230
|
+
warn(`${name}: file exceeds 8 MiB; skipped.`);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const buffer = await handle.readFile();
|
|
234
|
+
if (buffer.includes(0) && !/\.(pdf|docx)$/i.test(name)) continue;
|
|
235
|
+
try {
|
|
236
|
+
await add(name, buffer);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (error.status) throw error;
|
|
239
|
+
warn(`${name}: text extraction failed.`);
|
|
240
|
+
}
|
|
241
|
+
} finally {
|
|
242
|
+
await handle.close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
if (input.kind === 'text') await add('notes.txt', Buffer.from(input.text));
|
|
248
|
+
if (input.kind === 'files') {
|
|
249
|
+
const paths = new Set();
|
|
250
|
+
for (const file of input.files) {
|
|
251
|
+
insist(!paths.has(file.path), 'Duplicate synced file path.');
|
|
252
|
+
paths.add(file.path);
|
|
253
|
+
if (file.encoding === 'base64')
|
|
254
|
+
insist(
|
|
255
|
+
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.content),
|
|
256
|
+
'Invalid base64 content.',
|
|
257
|
+
);
|
|
258
|
+
safePath(file.path);
|
|
259
|
+
const buffer = Buffer.from(file.content, file.encoding);
|
|
260
|
+
if (/\.zip$/i.test(file.path))
|
|
261
|
+
await archive(buffer, input.files.length > 1 ? file.path.replace(/\.zip$/i, '') : '');
|
|
262
|
+
else await add(file.path, buffer);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (input.kind === 'local') {
|
|
266
|
+
const selected = path.resolve(input.path);
|
|
267
|
+
insist(
|
|
268
|
+
!(await fs.lstat(selected)).isSymbolicLink(),
|
|
269
|
+
'Select a real file or directory, not a symlink.',
|
|
270
|
+
);
|
|
271
|
+
locator = await fs.realpath(selected);
|
|
272
|
+
const stat = await fs.stat(locator);
|
|
273
|
+
insist(
|
|
274
|
+
!locator.split(path.sep).some((p) => SECRET.test(p) || SKIP.has(p)),
|
|
275
|
+
'Credential and dependency paths cannot be ingested.',
|
|
276
|
+
);
|
|
277
|
+
if (stat.isDirectory()) await walk(locator);
|
|
278
|
+
else {
|
|
279
|
+
insist(stat.isFile(), 'Select a regular file.');
|
|
280
|
+
insist(stat.size <= LIMITS.fileBytes, 'File exceeds 8 MiB.');
|
|
281
|
+
const buffer = await fs.readFile(locator);
|
|
282
|
+
if (/\.zip$/i.test(locator)) await archive(buffer);
|
|
283
|
+
else await add(path.basename(locator), buffer);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (input.kind === 'url') {
|
|
287
|
+
const document = await downloadDocument(input.url, { signal, maxBytes: LIMITS.fileBytes });
|
|
288
|
+
locator = new URL(input.url).toString();
|
|
289
|
+
if (/\.zip$/i.test(document.name)) await archive(document.buffer);
|
|
290
|
+
else await add(document.name, document.buffer);
|
|
291
|
+
if (document.url !== locator) warn(`Document retrieved from ${document.url}`);
|
|
292
|
+
}
|
|
293
|
+
if (input.kind === 'git') {
|
|
294
|
+
const url = new URL(input.url);
|
|
295
|
+
insist(
|
|
296
|
+
url.protocol === 'https:' &&
|
|
297
|
+
!url.username &&
|
|
298
|
+
!url.password &&
|
|
299
|
+
!url.search &&
|
|
300
|
+
!url.hash &&
|
|
301
|
+
!url.port &&
|
|
302
|
+
['github.com', 'gitlab.com', 'bitbucket.org'].includes(url.hostname),
|
|
303
|
+
'Use a public HTTPS repository on GitHub, GitLab or Bitbucket; use a local checkout for other hosts.',
|
|
304
|
+
);
|
|
305
|
+
insist(/^\/[\w.-]+\/[\w./-]+$/.test(url.pathname), 'Invalid repository path.');
|
|
306
|
+
locator = url.toString();
|
|
307
|
+
temp = await fs.mkdtemp(path.join(os.tmpdir(), 'aitm-ingest-'));
|
|
308
|
+
const checkout = path.join(temp, 'repo');
|
|
309
|
+
const env = {
|
|
310
|
+
...process.env,
|
|
311
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
312
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
313
|
+
GIT_CONFIG_GLOBAL: '/dev/null',
|
|
314
|
+
GIT_LFS_SKIP_SMUDGE: '1',
|
|
315
|
+
};
|
|
316
|
+
await gitRunner(
|
|
317
|
+
'git',
|
|
318
|
+
[
|
|
319
|
+
'-c',
|
|
320
|
+
'protocol.file.allow=never',
|
|
321
|
+
'-c',
|
|
322
|
+
'protocol.ext.allow=never',
|
|
323
|
+
'-c',
|
|
324
|
+
'core.hooksPath=/dev/null',
|
|
325
|
+
'clone',
|
|
326
|
+
'--depth',
|
|
327
|
+
'1',
|
|
328
|
+
'--single-branch',
|
|
329
|
+
'--no-recurse-submodules',
|
|
330
|
+
'--',
|
|
331
|
+
locator,
|
|
332
|
+
checkout,
|
|
333
|
+
],
|
|
334
|
+
{ signal, env, timeout: 60000, maxBuffer: 1024 * 1024 },
|
|
335
|
+
);
|
|
336
|
+
commit = (
|
|
337
|
+
await gitRunner('git', ['-C', checkout, 'rev-parse', 'HEAD'], { signal, env })
|
|
338
|
+
).stdout.trim();
|
|
339
|
+
await walk(await fs.realpath(checkout));
|
|
340
|
+
}
|
|
341
|
+
insist(
|
|
342
|
+
files.length > 0,
|
|
343
|
+
'No readable source content found. Select text/code, PDF, DOCX, a repository ZIP or a folder containing them.',
|
|
344
|
+
);
|
|
345
|
+
const sourceHash = hash(JSON.stringify(files.map((f) => [f.path, f.hash])));
|
|
346
|
+
return {
|
|
347
|
+
id: sourceId,
|
|
348
|
+
kind: input.kind,
|
|
349
|
+
label: input.label || path.basename(locator || 'Source'),
|
|
350
|
+
locator,
|
|
351
|
+
commit,
|
|
352
|
+
hash: sourceHash,
|
|
353
|
+
collectedAt: new Date().toISOString(),
|
|
354
|
+
files,
|
|
355
|
+
warnings,
|
|
356
|
+
};
|
|
357
|
+
} finally {
|
|
358
|
+
if (temp) await fs.rm(temp, { recursive: true, force: true });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Compatibility with saved assessments produced before complete-source batching.
|
|
363
|
+
export function needsFullSourceRun(project) {
|
|
364
|
+
if (project.sources.some((s) => s.warnings.some((w) => w.includes('excerpt truncated'))))
|
|
365
|
+
return true;
|
|
366
|
+
const ingest = project.artifacts.ingest;
|
|
367
|
+
if (
|
|
368
|
+
!ingest ||
|
|
369
|
+
ingest.generation?.sourceCoverage?.complete ||
|
|
370
|
+
ingest.generation?.sourceCoverage?.fromInventory
|
|
371
|
+
)
|
|
372
|
+
return false;
|
|
373
|
+
const files = project.sources.flatMap((s) => s.files);
|
|
374
|
+
const oldWeight = (file) =>
|
|
375
|
+
/\.(md|txt|pdf|docx)$/i.test(file.path) || /readme|spec|architect|whitepaper/i.test(file.path)
|
|
376
|
+
? 32
|
|
377
|
+
: 1;
|
|
378
|
+
const totalWeight = files.reduce((n, file) => n + oldWeight(file), 0);
|
|
379
|
+
return files.some(
|
|
380
|
+
(file) => file.text.length > Math.max(1, Math.floor((180000 * oldWeight(file)) / totalWeight)),
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export function sourceContext(project) {
|
|
385
|
+
return project.sources.flatMap((source) =>
|
|
386
|
+
source.files.map((file) => ({
|
|
387
|
+
id: file.id,
|
|
388
|
+
source: source.label,
|
|
389
|
+
sourceId: source.id,
|
|
390
|
+
sourceHash: source.hash,
|
|
391
|
+
path: file.path,
|
|
392
|
+
hash: file.hash,
|
|
393
|
+
text: file.text
|
|
394
|
+
.split('\n')
|
|
395
|
+
.map((line, i) => `${i + 1}: ${line}`)
|
|
396
|
+
.join('\n'),
|
|
397
|
+
excerptOnly: source.warnings.some((w) => w.startsWith(`${file.path}: excerpt truncated`)),
|
|
398
|
+
})),
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Split provider requests, never the stored evidence. Every line/character is sent,
|
|
403
|
+
// with original line numbers even when one unusually long line needs several parts.
|
|
404
|
+
export function sourceBatches(project, limit = 180000) {
|
|
405
|
+
insist(Number.isSafeInteger(limit) && limit >= 30, 'Invalid source batch size.');
|
|
406
|
+
const parts = [];
|
|
407
|
+
for (const file of sourceContext(project)) {
|
|
408
|
+
const chunks = [];
|
|
409
|
+
let chunk = '';
|
|
410
|
+
for (const numbered of file.text.split('\n')) {
|
|
411
|
+
const colon = numbered.indexOf(': ');
|
|
412
|
+
const prefix = numbered.slice(0, colon + 2);
|
|
413
|
+
let line = numbered.slice(colon + 2);
|
|
414
|
+
do {
|
|
415
|
+
const available = limit - prefix.length - 1;
|
|
416
|
+
const piece = prefix + line.slice(0, available);
|
|
417
|
+
if (chunk && chunk.length + piece.length + 1 > limit) {
|
|
418
|
+
chunks.push(chunk);
|
|
419
|
+
chunk = '';
|
|
420
|
+
}
|
|
421
|
+
chunk += (chunk ? '\n' : '') + piece;
|
|
422
|
+
line = line.slice(available);
|
|
423
|
+
} while (line.length);
|
|
424
|
+
}
|
|
425
|
+
if (chunk) chunks.push(chunk);
|
|
426
|
+
chunks.forEach((text, index) =>
|
|
427
|
+
parts.push({ ...file, text, part: index + 1, parts: chunks.length }),
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
const batches = [];
|
|
431
|
+
let batch = [],
|
|
432
|
+
size = 0;
|
|
433
|
+
for (const part of parts) {
|
|
434
|
+
if (batch.length && size + part.text.length > limit) {
|
|
435
|
+
batches.push(batch);
|
|
436
|
+
batch = [];
|
|
437
|
+
size = 0;
|
|
438
|
+
}
|
|
439
|
+
batch.push(part);
|
|
440
|
+
size += part.text.length;
|
|
441
|
+
}
|
|
442
|
+
if (batch.length) batches.push(batch);
|
|
443
|
+
return batches;
|
|
444
|
+
}
|