thumbgate 1.39.1 → 1.40.2
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/.claude-plugin/plugin.json +1 -1
- package/.well-known/llms.txt +2 -2
- package/.well-known/mcp/server-card.json +1 -1
- package/README.md +5 -4
- package/adapters/claude/.mcp.json +6 -2
- package/adapters/codex/config.toml +5 -0
- package/adapters/forge/forge.yaml +4 -4
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +82 -7
- package/adapters/opencode/opencode.json +1 -1
- package/bin/cli.js +128 -15
- package/config/brand-standards.json +131 -0
- package/config/gates/default.json +18 -1
- package/config/github-about.json +1 -1
- package/config/mcp-allowlists.json +16 -3
- package/config/merge-quality-checks.json +1 -0
- package/config/post-deploy-marketing-pages.json +3 -3
- package/config/schemas/task-outcome-receipt.schema.json +9 -0
- package/openapi/openapi.yaml +7 -3
- package/package.json +98 -31
- package/public/about.html +2 -2
- package/public/admin.html +771 -0
- package/public/agent-manager.html +3 -3
- package/public/agents-cost-savings.html +1 -1
- package/public/ai-malpractice-prevention.html +12 -12
- package/public/architecture.html +0 -1
- package/public/assets/diagrams/decision.svg +3 -3
- package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
- package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
- package/public/blog/git-at-agent-scale.html +2 -2
- package/public/blog/inside-your-boundary.html +1 -1
- package/public/blog/process-over-outcome-gates.html +1 -1
- package/public/case-studies.html +1 -2
- package/public/codex-enterprise.html +1 -1
- package/public/codex-plugin.html +1 -1
- package/public/dashboard.html +773 -481
- package/public/diagnostic.html +8 -3
- package/public/enterprise-governance.html +26 -174
- package/public/eval-scorecard.html +3 -4
- package/public/eval-scorecard.json +2 -2
- package/public/evaluations.html +0 -1
- package/public/founders.html +3 -3
- package/public/gaming-playbook.html +4 -4
- package/public/guide.html +3 -5
- package/public/index.html +181 -205
- package/public/install.html +12 -11
- package/public/js/buyer-intent.js +49 -8
- package/public/lessons.html +103 -46
- package/public/numbers.html +32 -33
- package/public/operator-framework.html +44 -72
- package/public/peter.html +3 -3
- package/public/platform-partners.html +1 -1
- package/public/pricing.html +61 -327
- package/public/pro.html +3 -1
- package/public/project-switcher.js +76 -0
- package/public/whitepaper.html +1 -2
- package/scripts/activation-quickstart.js +15 -3
- package/scripts/activation-tracker.js +280 -3
- package/scripts/agent-action-inventory.js +235 -143
- package/scripts/agent-operations-planner.js +1 -1
- package/scripts/agent-readiness.js +36 -6
- package/scripts/agentic-prompt-pipelines.js +901 -0
- package/scripts/analytics-report.js +363 -0
- package/scripts/analytics-window.js +7 -1
- package/scripts/async-job-runner.js +66 -11
- package/scripts/audit-trail.js +37 -24
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/auto-promote-gates.js +37 -27
- package/scripts/backfill-lesson-scopes.js +122 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/billing.js +889 -132
- package/scripts/bot-detection.js +112 -0
- package/scripts/brand-standards-gate.js +571 -0
- package/scripts/chatgpt-ads-readiness-pack.js +1 -1
- package/scripts/check-update.js +236 -0
- package/scripts/cli-schema.js +1 -1
- package/scripts/commercial-offer.js +2 -2
- package/scripts/contextfs.js +9 -3
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cross-encoder-reranker.js +4 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard-chat.js +11 -0
- package/scripts/dashboard.js +576 -169
- package/scripts/decision-journal.js +7 -4
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/docker-sandbox-planner.js +3 -3
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/export-dpo-pairs.js +12 -7
- package/scripts/feedback-aggregate.js +4 -0
- package/scripts/feedback-attribution.js +6 -4
- package/scripts/feedback-history-distiller.js +18 -6
- package/scripts/feedback-loop.js +255 -89
- package/scripts/feedback-paths.js +8 -1
- package/scripts/feedback-sanitizer.js +5 -0
- package/scripts/feedback-scope.js +106 -0
- package/scripts/feedback-session.js +8 -2
- package/scripts/filesystem-search.js +13 -8
- package/scripts/financial-control-plane.js +707 -45
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/gate-stats.js +8 -2
- package/scripts/gates-engine.js +694 -230
- package/scripts/generate-eval-scorecard.js +0 -1
- package/scripts/harness-tool-names.js +31 -5
- package/scripts/hybrid-feedback-context.js +5 -2
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/intervention-policy.js +2 -1
- package/scripts/latency-budget.js +164 -0
- package/scripts/lesson-canonical.js +2 -2
- package/scripts/lesson-db.js +55 -14
- package/scripts/lesson-graph.js +2 -1
- package/scripts/lesson-retrieval.js +95 -9
- package/scripts/lesson-search.js +86 -22
- package/scripts/lesson-synthesis.js +21 -5
- package/scripts/mailer/index.js +17 -1
- package/scripts/mailer/resend-mailer.js +213 -179
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/migrate-project-scope.js +209 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-integrity.js +436 -3
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/override-audit.js +2 -0
- package/scripts/owner-admin.js +338 -0
- package/scripts/pr-manager.js +194 -1
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/progressive-signoff.js +260 -0
- package/scripts/project-catalog.js +243 -0
- package/scripts/project-dashboard.js +61 -0
- package/scripts/project-evidence.js +172 -0
- package/scripts/project-identity.js +182 -0
- package/scripts/project-scope.js +381 -0
- package/scripts/prompt-guard.js +446 -52
- package/scripts/proof-report.js +232 -0
- package/scripts/provider-action-normalizer.js +14 -6
- package/scripts/pulse.js +80 -0
- package/scripts/rate-limiter.js +41 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/secret-redaction.js +171 -25
- package/scripts/secret-scanner.js +101 -42
- package/scripts/self-protection.js +2 -2
- package/scripts/seo-gsd.js +14 -14
- package/scripts/session-context-dedupe.js +66 -0
- package/scripts/session-report.js +120 -0
- package/scripts/settings-hierarchy.js +4 -2
- package/scripts/statusline-meta.js +34 -23
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/task-outcomes.js +29 -2
- package/scripts/telemetry-analytics.js +238 -13
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/scripts/thumbgate-search.js +23 -9
- package/scripts/tool-kpi-tracker.js +5 -2
- package/scripts/tool-registry.js +42 -1
- package/scripts/triage-savings-calculator.js +1 -1
- package/scripts/vector-store.js +4 -1
- package/scripts/verified-lessons.js +270 -0
- package/scripts/verify-marketing-pages-deployed.js +2 -2
- package/scripts/workflow-sentinel.js +29 -10
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/src/api/server.js +2371 -451
- package/src/feedback.js +21 -0
- package/src/hermes-sync-plane.js +2 -1
- package/src/index.js +2 -0
- package/src/lesson-search.js +9 -0
- package/src/mckinsey-top-company-ai-coding.js +493 -0
- package/src/mcp/server.js +3 -0
- package/src/mcp-writeguard.js +772 -11
- package/src/openshell-lovable-engine.js +1475 -0
- package/src/task-outcome.js +3 -0
- package/config/evals/agent-safety-eval.json +0 -447
- package/config/evals/retrieval-ranking-golden.json +0 -522
- package/config/progressive/01-wire-only.json +0 -11
- package/config/progressive/02-dashboard-empty-ok.json +0 -10
- package/config/progressive/03-one-lesson.json +0 -10
- package/config/progressive/04-warn-fires.json +0 -11
- package/config/progressive/05-strict-optional.json +0 -11
- package/config/progressive/README.md +0 -15
- package/public/assets/diagrams/agent-integration.png +0 -0
- package/public/assets/diagrams/thumbgate-architecture.png +0 -0
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { canonicalRemote, projectFromRemote } = require('./project-identity');
|
|
6
|
+
const TRUNCATED = /(?:\.{3}|…)\s*$/;
|
|
7
|
+
const inside = (candidate, root) => candidate === root || candidate.startsWith(root + path.sep);
|
|
8
|
+
const signature = (file) => { try { const s = fs.lstatSync(file, { bigint: true }); return `${s.ino}:${s.size}:${s.mtimeNs}`; } catch { return null; } };
|
|
9
|
+
|
|
10
|
+
function literalCommandPaths(command) {
|
|
11
|
+
if (typeof command !== 'string' || command.length > 16384 || TRUNCATED.test(command)) return [];
|
|
12
|
+
if (/[\x00-\x1f`$<>|]|[(){}]/.test(command)) return [];
|
|
13
|
+
const tokens = []; let token = ''; let quote = null;
|
|
14
|
+
for (let i = 0; i < command.length; i++) {
|
|
15
|
+
const char = command[i];
|
|
16
|
+
if (quote) { if (char === quote) quote = null; else if (char === '\\') return []; else token += char; continue; }
|
|
17
|
+
if (char === '"' || char === "'") { quote = char; continue; }
|
|
18
|
+
if (char === '\\') return [];
|
|
19
|
+
if (/\s/.test(char)) { if (token) tokens.push(token); token = ''; continue; }
|
|
20
|
+
if (char === ';' || char === '&') { if (token) tokens.push(token); token = ''; if (char === '&' && command[++i] !== '&') return []; tokens.push(';'); continue; }
|
|
21
|
+
token += char;
|
|
22
|
+
}
|
|
23
|
+
if (quote) return []; if (token) tokens.push(token);
|
|
24
|
+
const result = []; let segment = [];
|
|
25
|
+
const inspect = () => {
|
|
26
|
+
if (segment[0] === 'cd' && segment.length === 2) result.push({ value: segment[1], kind: 'command_directory' });
|
|
27
|
+
if (segment[0] === 'git' && segment[1] === '-C' && segment[2] && /^[a-z][a-z0-9-]*$/.test(segment[3] || '')) result.push({ value: segment[2], kind: 'command_directory' });
|
|
28
|
+
// Only absolute literal operands of these inspection commands are candidates.
|
|
29
|
+
if (['cat', 'head', 'tail', 'wc', 'ls'].includes(segment[0])) {
|
|
30
|
+
const operands = []; let valid = true; let endOptions = false;
|
|
31
|
+
for (let i = 1; i < segment.length; i++) {
|
|
32
|
+
const value = segment[i];
|
|
33
|
+
if (!endOptions && value === '--') { endOptions = true; continue; }
|
|
34
|
+
if (!endOptions && value.startsWith('-')) {
|
|
35
|
+
if (['head', 'tail'].includes(segment[0]) && ['-n', '-c'].includes(value)) { if (!/^[+-]?\d+$/.test(segment[++i] || '')) valid = false; }
|
|
36
|
+
else if (!(segment[0] === 'cat' ? /^-[AbEenstTuv]+$/ : segment[0] === 'wc' ? /^-[clmwL]+$/ : segment[0] === 'ls' ? /^-[aAbBcCdDfFgGhHiklLmnpqQrRsStuUvVxX1]+$/ : /$a/).test(value)) valid = false;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (path.isAbsolute(value)) operands.push({ value, kind: 'command_file' });
|
|
40
|
+
}
|
|
41
|
+
if (valid) result.push(...operands);
|
|
42
|
+
}
|
|
43
|
+
segment = [];
|
|
44
|
+
};
|
|
45
|
+
for (const part of [...tokens, ';']) { if (part === ';') inspect(); else segment.push(part); }
|
|
46
|
+
return result.filter((candidate) => path.isAbsolute(candidate.value));
|
|
47
|
+
}
|
|
48
|
+
function pathCandidates(record = {}) {
|
|
49
|
+
if (Array.isArray(record.pathCandidates)) return record.pathCandidates;
|
|
50
|
+
const result = [];
|
|
51
|
+
const add = (value, kind) => { if (typeof value === 'string' && value) result.push({ value, kind }); };
|
|
52
|
+
for (const source of [record, record.toolInput, record.toolInput?.tool_input, record.tool_input]) {
|
|
53
|
+
if (!source || typeof source !== 'object') continue;
|
|
54
|
+
for (const key of ['cwd', 'workingDirectory', 'workdir', 'repoPath', 'projectDir', 'hookWorkingDirectory']) add(source[key], 'directory');
|
|
55
|
+
for (const key of ['filePath', 'file_path']) add(source[key], 'file');
|
|
56
|
+
for (const key of ['filePaths', 'affectedFiles', 'changedFiles']) if (Array.isArray(source[key])) for (const value of source[key]) add(value, 'file');
|
|
57
|
+
}
|
|
58
|
+
for (const value of [record.scope?.projectId, record.registryProject]) if (typeof value === 'string' && path.isAbsolute(value)) add(value, 'directory');
|
|
59
|
+
for (const command of [record.toolInput?.command, record.toolInput?.tool_input?.command, record.tool_input?.command]) result.push(...literalCommandPaths(command));
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
function provenanceReason(record, options) {
|
|
63
|
+
if (record.imported || record.importedFrom || record.syncedFrom || record.metadata?.importedFrom || record.provenance?.imported) return 'foreign_provenance';
|
|
64
|
+
const origin = [record.source, record.sourceType, record.provenance?.origin, record.metadata?.sourceType].filter((value) => typeof value === 'string').join(' ');
|
|
65
|
+
if (/\b(imported?|remote|cloud[-_ ]sync|hermes[-_ ]sync)\b/i.test(origin)) return 'foreign_provenance';
|
|
66
|
+
const machines = [record.sourceMachineId, record.machineId, record.metadata?.machineId, record.provenance?.machineId].filter(Boolean);
|
|
67
|
+
if (new Set(machines).size > 1) return 'foreign_machine';
|
|
68
|
+
const machine = machines[0];
|
|
69
|
+
if (machine && (!options.sourceMachineId || machine !== options.sourceMachineId)) return 'foreign_machine';
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
function createPathEvidence(options = {}) {
|
|
73
|
+
const enabled = options.trustedLocalSource === true;
|
|
74
|
+
const roots = enabled ? (options.allowedRoots || []).flatMap((root) => { try { return [path.resolve(root), fs.realpathSync(root)]; } catch { return []; } }) : [];
|
|
75
|
+
const limits = { candidates: 4096, ancestors: 32, pathsPerRow: 16, pathBytes: 4096, fileBytes: 256 * 1024, totalBytes: 16 * 1024 * 1024, ...(options.limits || {}) };
|
|
76
|
+
const cache = new Map(); const diagnostics = {}; let bytes = 0; let probes = 0;
|
|
77
|
+
const failure = (reason) => ({ descriptor: null, reason });
|
|
78
|
+
const count = (reason) => { diagnostics[reason] = (diagnostics[reason] || 0) + 1; };
|
|
79
|
+
function safe(file) { return roots.some((root) => inside(path.resolve(file), root)); }
|
|
80
|
+
function metadata(file, files) {
|
|
81
|
+
if (!safe(file)) throw new Error('unsafe_path');
|
|
82
|
+
const stat = fs.lstatSync(file);
|
|
83
|
+
if (!stat.isFile() || stat.isSymbolicLink() || !safe(fs.realpathSync(file))) throw new Error('unsafe_metadata');
|
|
84
|
+
if (stat.size > limits.fileBytes || bytes + stat.size > limits.totalBytes) throw new Error('probe_budget_exceeded');
|
|
85
|
+
const before = signature(file); const value = fs.readFileSync(file, 'utf8'); bytes += stat.size;
|
|
86
|
+
if (signature(file) !== before) throw new Error('metadata_changed');
|
|
87
|
+
files.push([file, before]); return value;
|
|
88
|
+
}
|
|
89
|
+
function configRemotes(text, remotes) {
|
|
90
|
+
let section = null;
|
|
91
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
92
|
+
const line = raw.trim(); if (!line || /^[#;]/.test(line)) continue;
|
|
93
|
+
if (/^\[(?:include(?:if)?|url)\b/i.test(line) || /\\$/.test(line)) throw new Error('unsupported_git_metadata');
|
|
94
|
+
if (line.startsWith('[')) {
|
|
95
|
+
if (!/^\[[a-zA-Z][\w.-]*(?:\s+"[^"\\]*")?\]\s*(?:[#;].*)?$/.test(line)) throw new Error('unsupported_git_metadata');
|
|
96
|
+
const match = line.match(/^\[remote\s+"([^"\r\n]+)"\]\s*(?:[#;].*)?$/i); if (/^\[remote\b/i.test(line) && !match) throw new Error('unsupported_git_metadata'); section = match ? match[1] : null; continue;
|
|
97
|
+
}
|
|
98
|
+
if (!section) continue;
|
|
99
|
+
const match = line.match(/^url\s*=\s*(.*?)\s*$/i); if (!match) continue;
|
|
100
|
+
let value = match[1];
|
|
101
|
+
if (value.startsWith('"')) { if (!/^"[^"\\]*"$/.test(value)) throw new Error('unsupported_git_metadata'); value = value.slice(1, -1); }
|
|
102
|
+
else value = value.replace(/\s+[#;].*$/, '');
|
|
103
|
+
if (!canonicalRemote(value)) throw new Error('unsupported_git_metadata');
|
|
104
|
+
if (!remotes.has(section)) remotes.set(section, []); remotes.get(section).push(value);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function probe(value, kind) {
|
|
108
|
+
if (/redacted|masked|\[filtered\]|[*?<>]/i.test(value)) return failure('redacted_or_expanding_path');
|
|
109
|
+
if (!path.isAbsolute(value) || value.startsWith('//') || /[\x00-\x1f]/.test(value) || Buffer.byteLength(value) > limits.pathBytes || TRUNCATED.test(value)) return failure(TRUNCATED.test(value) ? 'truncated_path' : 'unsafe_path');
|
|
110
|
+
if (!safe(value)) return failure('outside_approved_roots');
|
|
111
|
+
const cacheKey = kind + '\0' + value; const cached = cache.get(cacheKey);
|
|
112
|
+
if (cached && cached.files.every(([file, stamp]) => signature(file) === stamp)) return cached.result;
|
|
113
|
+
if (!cache.has(cacheKey) && cache.size >= limits.candidates) return failure('probe_budget_exceeded');
|
|
114
|
+
probes++; const files = []; let result;
|
|
115
|
+
try {
|
|
116
|
+
let directory = value;
|
|
117
|
+
try { if (!fs.statSync(directory).isDirectory()) directory = path.dirname(directory); }
|
|
118
|
+
catch { if (!kind.endsWith('file') && kind !== 'file') throw new Error('missing_path'); directory = path.dirname(value); if (!fs.statSync(directory).isDirectory()) throw new Error('missing_path'); }
|
|
119
|
+
directory = fs.realpathSync(directory); if (!safe(directory)) throw new Error('unsafe_path');
|
|
120
|
+
for (let depth = 0; depth < limits.ancestors && safe(directory); depth++) {
|
|
121
|
+
const marker = path.join(directory, '.git');
|
|
122
|
+
if (fs.existsSync(marker)) {
|
|
123
|
+
const stat = fs.lstatSync(marker); if (stat.isSymbolicLink()) throw new Error('unsafe_metadata');
|
|
124
|
+
let gitDir = marker;
|
|
125
|
+
if (stat.isFile()) { const pointer = metadata(marker, files).trim().match(/^gitdir:\s*(.+)$/); if (!pointer) throw new Error('unsupported_git_metadata'); gitDir = path.resolve(directory, pointer[1]); }
|
|
126
|
+
if (!safe(gitDir) || !safe(fs.realpathSync(gitDir))) throw new Error('unsafe_metadata');
|
|
127
|
+
let common = gitDir; const commonFile = path.join(gitDir, 'commondir');
|
|
128
|
+
files.push([commonFile, signature(commonFile)]);
|
|
129
|
+
if (fs.existsSync(commonFile)) common = path.resolve(gitDir, metadata(commonFile, files).trim());
|
|
130
|
+
if (!safe(common) || !safe(fs.realpathSync(common))) throw new Error('unsafe_metadata');
|
|
131
|
+
const remotes = new Map(); configRemotes(metadata(path.join(common, 'config'), files), remotes);
|
|
132
|
+
const worktreeConfig = path.join(gitDir, 'config.worktree'); files.push([worktreeConfig, signature(worktreeConfig)]); if (fs.existsSync(worktreeConfig)) configRemotes(metadata(worktreeConfig, files), remotes);
|
|
133
|
+
const name = remotes.has('origin') ? 'origin' : [...remotes.keys()].sort((a, b) => a.localeCompare(b))[0];
|
|
134
|
+
if (!name) throw new Error('remote_missing');
|
|
135
|
+
const urls = remotes.get(name); if (new Set(urls.map(canonicalRemote)).size !== 1) throw new Error('conflicting_path_remotes');
|
|
136
|
+
result = { descriptor: { ...projectFromRemote(urls[0]), identitySource: 'path_remote_current' }, reason: null }; break;
|
|
137
|
+
}
|
|
138
|
+
const parent = path.dirname(directory); if (parent === directory) break; directory = parent;
|
|
139
|
+
}
|
|
140
|
+
if (!result) result = failure('repository_missing');
|
|
141
|
+
} catch (error) { result = failure(['ENOENT', 'ENOTDIR'].includes(error.code) ? 'missing_path' : error.message); }
|
|
142
|
+
cache.set(cacheKey, { result, files }); return result;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
resolve(record) {
|
|
146
|
+
const candidates = pathCandidates(record); if (!candidates.length) return failure('no_path_evidence');
|
|
147
|
+
if (!enabled || !roots.length) return failure('path_probe_disabled');
|
|
148
|
+
const foreign = provenanceReason(record, options); if (foreign) { count(foreign); return failure(foreign); }
|
|
149
|
+
if (candidates.length > limits.pathsPerRow) { count('probe_budget_exceeded'); return failure('probe_budget_exceeded'); }
|
|
150
|
+
const directories = candidates.filter((candidate) => candidate.kind === 'directory' && path.isAbsolute(candidate.value));
|
|
151
|
+
const results = candidates.map((candidate) => {
|
|
152
|
+
let value = candidate.value;
|
|
153
|
+
if (!path.isAbsolute(value) && candidate.kind === 'file' && directories.length === 1) { value = path.resolve(directories[0].value, value); if (!inside(value, path.resolve(directories[0].value))) return failure('unsafe_path'); }
|
|
154
|
+
return probe(value, candidate.kind);
|
|
155
|
+
});
|
|
156
|
+
const failed = results.find((result) => result.reason && result.reason !== 'remote_missing' && result.reason !== 'repository_missing' && result.reason !== 'missing_path');
|
|
157
|
+
if (failed) { count(failed.reason); return failed; }
|
|
158
|
+
const descriptors = results.map((result) => result.descriptor).filter(Boolean);
|
|
159
|
+
if (new Set(descriptors.map((descriptor) => descriptor.projectKey)).size > 1) { count('conflicting_paths'); return failure('conflicting_paths'); }
|
|
160
|
+
if (descriptors.length) return { descriptor: descriptors[0], reason: null };
|
|
161
|
+
const reason = results[0]?.reason || 'no_path_evidence'; count(reason); return failure(reason);
|
|
162
|
+
},
|
|
163
|
+
report: () => ({ probes, cachedCandidates: cache.size, metadataBytes: bytes, reasons: { ...diagnostics } }),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
// Only server/operator configuration may attest a local source. HTTP-selected roots
|
|
167
|
+
// and hosted tenants never acquire this policy from a path supplied by a client.
|
|
168
|
+
function localRuntimeEvidenceOptions({ feedbackDir, sourceRoot, hosted, homeDir = require('node:os').homedir() } = {}) {
|
|
169
|
+
if (hosted || !feedbackDir || !sourceRoot || path.resolve(feedbackDir) !== path.resolve(sourceRoot)) return {};
|
|
170
|
+
return { localPathEvidence: { trustedLocalSource: true, allowedRoots: [path.join(homeDir, 'workspace'), path.join(homeDir, '.herdr', 'worktrees')] } };
|
|
171
|
+
}
|
|
172
|
+
module.exports = { localRuntimeEvidenceOptions, pathCandidates, literalCommandPaths, provenanceReason, createPathEvidence };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const { execFileSync } = require('node:child_process');
|
|
8
|
+
|
|
9
|
+
const KEY_RE = /^(?:(?:repo|local|legacy)_[a-f0-9]{64}|unassigned)$/;
|
|
10
|
+
const UNASSIGNED = Object.freeze({ projectKey: 'unassigned', projectName: 'Unassigned (before project tracking)', identitySource: 'unassigned' });
|
|
11
|
+
const hash = (value) => crypto.createHash('sha256').update(String(value)).digest('hex');
|
|
12
|
+
const validProjectKey = (value) => typeof value === 'string' && KEY_RE.test(value);
|
|
13
|
+
function invalid(message) { const error = new Error(message); error.statusCode = 400; return error; }
|
|
14
|
+
function safeProjectName(value, fallback = 'Project') {
|
|
15
|
+
const name = String(value || '').replace(/[\u0000-\u001f\u007f]/g, '').trim();
|
|
16
|
+
if (!name || /[@\\]|:\/\/|(?:^|\s)\//.test(name)) return fallback;
|
|
17
|
+
return name.slice(0, 120);
|
|
18
|
+
}
|
|
19
|
+
function canonicalRemote(value) {
|
|
20
|
+
if (typeof value !== 'string' || !value.trim()) return null;
|
|
21
|
+
let raw = value.trim();
|
|
22
|
+
if (!raw.includes('://') && /^(?:[^@/:]+@)?[^/:]+:.+/.test(raw)) {
|
|
23
|
+
raw = 'ssh://' + raw.replace(/^((?:[^@/:]+@)?[^/:]+):/, '$1/');
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const url = new URL(raw);
|
|
27
|
+
if (!['https:', 'http:', 'ssh:', 'git:'].includes(url.protocol) || !url.hostname) return null;
|
|
28
|
+
const host = url.hostname.toLowerCase();
|
|
29
|
+
const port = url.port && !((url.protocol === 'ssh:' && url.port === '22') || (url.protocol === 'git:' && url.port === '9418')) ? ':' + url.port : '';
|
|
30
|
+
let repo = url.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
|
|
31
|
+
if (!repo || repo.split('/').some((part) => !part || part === '..' || part === '.')) return null;
|
|
32
|
+
if (host === 'github.com') repo = repo.toLowerCase();
|
|
33
|
+
return `${host}${port}/${repo}`;
|
|
34
|
+
} catch { return null; }
|
|
35
|
+
}
|
|
36
|
+
function projectFromRemote(remote, name) {
|
|
37
|
+
const canonical = canonicalRemote(remote);
|
|
38
|
+
if (!canonical) throw invalid('Invalid project remote');
|
|
39
|
+
return { projectKey: `repo_${hash(canonical)}`, projectName: safeProjectName(name, canonical.split('/').slice(1).join('/')), identitySource: 'remote' };
|
|
40
|
+
}
|
|
41
|
+
function machineIdentity(options = {}) {
|
|
42
|
+
if (options.machineId) return String(options.machineId);
|
|
43
|
+
for (const file of ['/etc/machine-id', '/var/lib/dbus/machine-id']) {
|
|
44
|
+
try { const id = fs.readFileSync(file, 'utf8').trim(); if (id) return id; } catch { /* OS dependent */ }
|
|
45
|
+
}
|
|
46
|
+
if (process.platform === 'darwin') {
|
|
47
|
+
try { const match = execFileSync('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 1500 }).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/); if (match) return match[1]; } catch { /* fallback below */ }
|
|
48
|
+
}
|
|
49
|
+
const file = options.machineIdPath || path.join(os.homedir(), '.thumbgate', 'machine-id');
|
|
50
|
+
try { return fs.readFileSync(file, 'utf8').trim(); } catch { /* first local resolution */ }
|
|
51
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
52
|
+
try { fs.writeFileSync(file, crypto.randomUUID(), { flag: 'wx', mode: 0o600 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
53
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
54
|
+
}
|
|
55
|
+
function git(cwd, args) {
|
|
56
|
+
try { return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return ''; } // NOSONAR: read-only git lookup with fixed argv and no shell; git comes from PATH on purpose
|
|
57
|
+
}
|
|
58
|
+
const localProjectCache = new Map();
|
|
59
|
+
// Fingerprint of the git config that decides identity (remotes, worktree link). A changed remote changes the stamp, so a stale entry is never served.
|
|
60
|
+
function gitConfigStamp(cwd) {
|
|
61
|
+
let dir = path.resolve(cwd);
|
|
62
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
63
|
+
const dotGit = path.join(dir, '.git');
|
|
64
|
+
try {
|
|
65
|
+
const stat = fs.statSync(dotGit);
|
|
66
|
+
let gitDir = dotGit;
|
|
67
|
+
const parts = [];
|
|
68
|
+
if (stat.isFile()) {
|
|
69
|
+
const match = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/m);
|
|
70
|
+
if (!match) return null;
|
|
71
|
+
gitDir = path.resolve(dir, match[1].trim());
|
|
72
|
+
parts.push(`${dotGit}:${stat.mtimeMs}`);
|
|
73
|
+
}
|
|
74
|
+
let common = gitDir;
|
|
75
|
+
try { common = path.resolve(gitDir, fs.readFileSync(path.join(gitDir, 'commondir'), 'utf8').trim()); } catch { /* not a linked worktree */ }
|
|
76
|
+
const config = fs.statSync(path.join(common, 'config'));
|
|
77
|
+
parts.push(`${gitDir}`, `${common}:${config.mtimeMs}:${config.size}`);
|
|
78
|
+
return parts.join('|');
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') return null;
|
|
81
|
+
}
|
|
82
|
+
const parent = path.dirname(dir);
|
|
83
|
+
if (parent === dir) return null;
|
|
84
|
+
dir = parent;
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
// Each resolution spawns up to four git processes; tool calls and audit events resolve on every event, so memoize per cwd.
|
|
89
|
+
function resolveLocalProject(cwd = process.cwd(), options = {}) {
|
|
90
|
+
const stamp = gitConfigStamp(cwd);
|
|
91
|
+
if (!stamp) return resolveLocalProjectUncached(cwd, options);
|
|
92
|
+
const key = `${path.resolve(cwd)}\0${options.machineId || ''}\0${options.machineIdPath || ''}`;
|
|
93
|
+
const hit = localProjectCache.get(key);
|
|
94
|
+
if (hit && hit.stamp === stamp) return { ...hit.value };
|
|
95
|
+
const value = resolveLocalProjectUncached(cwd, options);
|
|
96
|
+
localProjectCache.set(key, { stamp, value });
|
|
97
|
+
return { ...value };
|
|
98
|
+
}
|
|
99
|
+
function resolveLocalProjectUncached(cwd = process.cwd(), options = {}) {
|
|
100
|
+
let root = git(cwd, ['rev-parse', '--show-toplevel']) || path.resolve(cwd);
|
|
101
|
+
try { root = fs.realpathSync(root); } catch { return { ...UNASSIGNED }; }
|
|
102
|
+
const common = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
103
|
+
const remotes = git(root, ['remote']).split('\n').filter(Boolean).sort((a, b) => a.localeCompare(b));
|
|
104
|
+
const remote = git(root, ['remote', 'get-url', remotes.includes('origin') ? 'origin' : remotes[0] || 'origin']);
|
|
105
|
+
if (canonicalRemote(remote)) return projectFromRemote(remote);
|
|
106
|
+
// Common git metadata gives remote-less worktrees the identity of their repository.
|
|
107
|
+
if (common && path.basename(common) === '.git') root = path.dirname(common);
|
|
108
|
+
return { projectKey: `local_${hash(`${machineIdentity(options)}\0${root}`)}`, projectName: safeProjectName(path.basename(root), 'Local project'), identitySource: 'local' };
|
|
109
|
+
}
|
|
110
|
+
function legacyAlias(record = {}, options = {}) {
|
|
111
|
+
const registry = options.recordType === 'agent-registry.jsonl' || record.recordType === 'agent-registry.jsonl';
|
|
112
|
+
const value = record.scope?.projectId || record.metadata?.project || record.metadata?.repo || record.projectId || (registry ? record.registryProject || record.project : null);
|
|
113
|
+
if (typeof value !== 'string' || !value.trim() || /^(unknown|global|default|none|null|unassigned|n\/a)$/i.test(value.trim())) return null;
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
function recordedRemotes(record = {}) {
|
|
117
|
+
return [record.remoteUrl, record.remote, record.metadata?.remoteUrl, record.metadata?.remote, record.scope?.remoteUrl, record.scope?.remote].filter((value) => canonicalRemote(value));
|
|
118
|
+
}
|
|
119
|
+
function legacyDescriptor(alias) { return { projectKey: `legacy_${hash(alias)}`, projectName: safeProjectName(alias, 'Legacy project') + ' (legacy)', identitySource: 'legacy' }; }
|
|
120
|
+
function resolveProjectEvidence(record = {}, options = {}) {
|
|
121
|
+
const outcome = (descriptor, evidence, reason = null, anchorEvidence = null) => ({ descriptor, evidence, reason, anchorEvidence });
|
|
122
|
+
const missing = (reason) => outcome({ ...UNASSIGNED }, 'unassigned', reason);
|
|
123
|
+
if (validProjectKey(record.projectKey) && record.projectKey !== 'unassigned') return outcome({ projectKey: record.projectKey, projectName: safeProjectName(record.projectName, 'Project'), identitySource: record.identitySource || 'recorded' }, 'recorded_key');
|
|
124
|
+
const remotes = recordedRemotes(record);
|
|
125
|
+
if (new Set(remotes.map(canonicalRemote)).size > 1) return missing('conflicting_recorded_remotes');
|
|
126
|
+
if (remotes.length) return outcome(projectFromRemote(remotes[0], record.projectName), 'recorded_remote');
|
|
127
|
+
const recordType = options.recordType || record.recordType;
|
|
128
|
+
const alias = legacyAlias(record, options);
|
|
129
|
+
const references = [];
|
|
130
|
+
if (record.sourceFeedbackId) references.push([options.feedbackById?.get(record.sourceFeedbackId), 'feedback_reference']);
|
|
131
|
+
if (record.sourceLessonId) references.push([options.lessonById?.get(record.sourceLessonId), 'lesson_reference']);
|
|
132
|
+
const agentId = record.agentId || (recordType === 'observed-agents.jsonl' ? record.id : null);
|
|
133
|
+
if (agentId) references.push([options.registryById?.get(agentId), 'agent_registry_reference']);
|
|
134
|
+
const usable = references.filter(([candidate]) => candidate && candidate.projectKey !== 'unassigned');
|
|
135
|
+
if (references.some(([candidate]) => candidate?.ambiguous)) return missing('ambiguous_source_id');
|
|
136
|
+
const canonical = usable.map(([candidate]) => candidate).filter((candidate) => candidate && /^(repo|local)_/.test(candidate.projectKey));
|
|
137
|
+
if (new Set(canonical.map((candidate) => candidate.projectKey)).size > 1) return missing('conflicting_references');
|
|
138
|
+
// A directory's git remote today is not evidence of what it was when the row was written, so paths never attribute.
|
|
139
|
+
if (new Set(usable.map(([candidate]) => candidate.projectKey)).size > 1) return missing('conflicting_references');
|
|
140
|
+
if (usable.length) { const [candidate, evidence] = usable[0]; return outcome({ projectKey: candidate.projectKey, projectName: candidate.projectName, identitySource: evidence }, evidence, null, candidate.evidence || candidate.identitySource); }
|
|
141
|
+
const session = options.sessionLookup?.(record);
|
|
142
|
+
if (alias && session?.projectKey === legacyDescriptor(alias).projectKey) return outcome(legacyDescriptor(alias), recordType === 'agent-registry.jsonl' ? 'registry_legacy_project' : 'legacy_scope');
|
|
143
|
+
if (session?.ambiguous) return missing('conflicting_session');
|
|
144
|
+
if (session?.projectKey && session.projectKey !== 'unassigned') return outcome({ projectKey: session.projectKey, projectName: session.projectName, identitySource: 'session_anchor' }, 'session_anchor', null, session.evidence);
|
|
145
|
+
if (alias) return outcome(legacyDescriptor(alias), recordType === 'agent-registry.jsonl' ? 'registry_legacy_project' : 'legacy_scope');
|
|
146
|
+
return missing('no_admissible_evidence');
|
|
147
|
+
}
|
|
148
|
+
function projectForRecord(record = {}, options = {}) { return resolveProjectEvidence(record, options).descriptor; }
|
|
149
|
+
// A label shared with another row is a guess, so no label-to-repo map is built.
|
|
150
|
+
function buildAliases() { return new Map(); }
|
|
151
|
+
function matchesProject(record, projectKey, options = {}) { return projectKey == null || projectForRecord(record, options).projectKey === projectKey; }
|
|
152
|
+
function isGeneratedGate(gate = {}) { return Boolean(gate.autoPromoted || gate.generated || gate.sourceLessonId || gate.sourceFeedbackId || gate.source === 'auto-promote' || /^auto[-_]/.test(gate.id || '')); }
|
|
153
|
+
function gateAppliesToProject(gate, projectKey) {
|
|
154
|
+
if (gate.active === false || gate.enabled === false) return false;
|
|
155
|
+
if (gate.scope === 'global') return true;
|
|
156
|
+
// Enforcement must not vanish on upgrade: a gate with no recorded project keeps applying everywhere.
|
|
157
|
+
if (gate.legacyUnscoped) return true;
|
|
158
|
+
if (gate.scope === 'project' || validProjectKey(gate.projectKey)) return validProjectKey(gate.projectKey) && gate.projectKey !== 'unassigned' && gate.projectKey === (projectKey || 'unassigned');
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
function parseProjectSelection(searchParams, headers = {}, body = {}) {
|
|
162
|
+
const values = searchParams?.getAll('project') || [];
|
|
163
|
+
if (values.length > 1) throw invalid('Repeated project selection');
|
|
164
|
+
const supplied = [...values, headers['x-thumbgate-project'], body.projectKey].filter((value) => value !== undefined && value !== null);
|
|
165
|
+
const normalized = supplied.map((value) => {
|
|
166
|
+
if (value === 'all') return null;
|
|
167
|
+
if (!validProjectKey(value)) throw invalid('Invalid project key');
|
|
168
|
+
return value;
|
|
169
|
+
});
|
|
170
|
+
if (normalized.some((value) => value !== normalized[0])) throw invalid('Conflicting project selections');
|
|
171
|
+
return normalized.length ? normalized[0] : null;
|
|
172
|
+
}
|
|
173
|
+
function projectForCapture(input = {}, options = {}) {
|
|
174
|
+
if (input.projectKey != null && !validProjectKey(input.projectKey)) throw invalid('Invalid project key');
|
|
175
|
+
const remote = input.remoteUrl ? projectFromRemote(input.remoteUrl, input.projectName) : null;
|
|
176
|
+
if (remote && input.projectKey && remote.projectKey !== input.projectKey) throw invalid('Project key does not match remote');
|
|
177
|
+
if (options.hosted) return remote || (input.projectKey ? projectForRecord(input) : { ...UNASSIGNED });
|
|
178
|
+
const descriptor = resolveLocalProject(input.cwd || options.cwd || process.cwd(), options);
|
|
179
|
+
if ((input.projectKey && input.projectKey !== descriptor.projectKey) || (remote && remote.projectKey !== descriptor.projectKey)) throw invalid('Project key does not match execution directory');
|
|
180
|
+
return descriptor;
|
|
181
|
+
}
|
|
182
|
+
module.exports = { KEY_RE, UNASSIGNED, hash, validProjectKey, safeProjectName, canonicalRemote, projectFromRemote, resolveLocalProject, legacyAlias, recordedRemotes, resolveProjectEvidence, projectForRecord, buildAliases, matchesProject, gateAppliesToProject, isGeneratedGate, parseProjectSelection, projectForCapture };
|