@feltdb/feltkit 0.3.24 → 0.3.25
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/dist/app.d.ts +75 -0
- package/dist/app.js +69 -1
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +1 -1
- package/dist/appboundry/build.js +18 -4
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.d.ts +11 -0
- package/dist/appboundry/guest.js +20 -0
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/cli/main.js +59 -2
- package/dist/cli/main.js.map +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/measure/index.d.ts +117 -0
- package/dist/measure/index.js +479 -0
- package/dist/measure/index.js.map +1 -0
- package/dist/runtime/runtime.js +0 -7
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/transactions.js +10 -2
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/server/project.d.ts +2 -0
- package/dist/server/project.js +9 -5
- package/dist/server/project.js.map +1 -1
- package/docs/MEASURE.md +144 -0
- package/docs/README.md +3 -2
- package/docs/TRANSACTIONS.md +42 -0
- package/docs/UPSTREAM-GAPS.md +1 -1
- package/package.json +2 -2
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-build/SKILL.md +14 -2
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
export declare const MEASURE_SCHEMA = "feltkit.measure/1";
|
|
2
|
+
export declare const MEASURE_CONFIG = "feltkit.measure.json";
|
|
3
|
+
export declare const SCAFFOLD_MANIFEST = "feltkit.scaffold.json";
|
|
4
|
+
/** The classes. `excluded` is counted but is not code (docs, images, lockfiles). */
|
|
5
|
+
export declare const CLASSES: readonly ["domain", "experience", "infrastructure", "generated", "configuration", "tests", "third-party", "platform", "excluded", "unclassified"];
|
|
6
|
+
export type MeasureClass = (typeof CLASSES)[number];
|
|
7
|
+
export declare const CLASS_MEANING: Record<MeasureClass, string>;
|
|
8
|
+
/** Classes the application's own team writes and maintains (tests are reported beside them). */
|
|
9
|
+
export declare const AUTHORED: MeasureClass[];
|
|
10
|
+
export interface MeasureDeclaration {
|
|
11
|
+
/** A path or glob relative to the project (`*` within a segment, `**` across segments). */
|
|
12
|
+
path: string;
|
|
13
|
+
class: MeasureClass;
|
|
14
|
+
reason: string;
|
|
15
|
+
}
|
|
16
|
+
export interface MeasureConfig {
|
|
17
|
+
classify?: MeasureDeclaration[];
|
|
18
|
+
/** Where the scaffold manifest is (default feltkit.scaffold.json). */
|
|
19
|
+
scaffold?: string;
|
|
20
|
+
/** Where `--write` keeps the report and `--check` compares it (default none). */
|
|
21
|
+
report?: string;
|
|
22
|
+
/** Acknowledged infrastructure findings: `<finding id>:<file>` → why it stays. */
|
|
23
|
+
acknowledged?: Record<string, string>;
|
|
24
|
+
}
|
|
25
|
+
export interface MeasuredFile {
|
|
26
|
+
path: string;
|
|
27
|
+
class: MeasureClass;
|
|
28
|
+
basis: string;
|
|
29
|
+
lines: number;
|
|
30
|
+
scaffold?: "unmodified" | "modified";
|
|
31
|
+
}
|
|
32
|
+
export interface Finding {
|
|
33
|
+
id: string;
|
|
34
|
+
title: string;
|
|
35
|
+
file: string;
|
|
36
|
+
line: number;
|
|
37
|
+
evidence: string;
|
|
38
|
+
/** The platform capability that does this, or null when the platform has none yet (a gap candidate). */
|
|
39
|
+
platform: string | null;
|
|
40
|
+
acknowledged?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface Check {
|
|
43
|
+
name: string;
|
|
44
|
+
ok: boolean;
|
|
45
|
+
detail: string;
|
|
46
|
+
fix?: string;
|
|
47
|
+
}
|
|
48
|
+
export interface MeasureReport {
|
|
49
|
+
schema: typeof MEASURE_SCHEMA;
|
|
50
|
+
app: {
|
|
51
|
+
name: string | null;
|
|
52
|
+
feltkit: string | null;
|
|
53
|
+
installed: string | null;
|
|
54
|
+
};
|
|
55
|
+
method: {
|
|
56
|
+
files: string;
|
|
57
|
+
lines: string;
|
|
58
|
+
consumption: string;
|
|
59
|
+
findings: string;
|
|
60
|
+
};
|
|
61
|
+
provenance: {
|
|
62
|
+
scaffold: null | {
|
|
63
|
+
manifest: string;
|
|
64
|
+
generator: string;
|
|
65
|
+
version: string;
|
|
66
|
+
template: string;
|
|
67
|
+
files: number;
|
|
68
|
+
unmodified: number;
|
|
69
|
+
modified: number;
|
|
70
|
+
missing: number;
|
|
71
|
+
};
|
|
72
|
+
generated: {
|
|
73
|
+
file: string;
|
|
74
|
+
current: boolean;
|
|
75
|
+
} | null;
|
|
76
|
+
skills: Array<{
|
|
77
|
+
name: string;
|
|
78
|
+
installedBy: string | null;
|
|
79
|
+
current: boolean | null;
|
|
80
|
+
}>;
|
|
81
|
+
};
|
|
82
|
+
totals: Record<MeasureClass, {
|
|
83
|
+
files: number;
|
|
84
|
+
lines: number;
|
|
85
|
+
}>;
|
|
86
|
+
authored: {
|
|
87
|
+
files: number;
|
|
88
|
+
lines: number;
|
|
89
|
+
};
|
|
90
|
+
definitions: {
|
|
91
|
+
app: Record<string, number>;
|
|
92
|
+
collections: string[];
|
|
93
|
+
};
|
|
94
|
+
consumption: Array<{
|
|
95
|
+
api: string;
|
|
96
|
+
callSites: number;
|
|
97
|
+
files: number;
|
|
98
|
+
}>;
|
|
99
|
+
findings: Finding[];
|
|
100
|
+
checks: Check[];
|
|
101
|
+
files: MeasuredFile[];
|
|
102
|
+
}
|
|
103
|
+
/** The files the repository is made of: tracked plus untracked-not-ignored (git), or a walk. */
|
|
104
|
+
export declare function projectFiles(projectDir: string): string[];
|
|
105
|
+
/** Lines that are code: not blank and not only a comment. JSON/YAML/TOML count non-blank lines. */
|
|
106
|
+
export declare function codeLines(path: string, text: string): number;
|
|
107
|
+
/** `*` matches within a path segment, `**` across segments. */
|
|
108
|
+
export declare function globToRegExp(glob: string): RegExp;
|
|
109
|
+
/** Measure the application at projectDir. `shippedSkills` is the platform's current skill set, if known. */
|
|
110
|
+
export declare function measure(projectDir: string, options?: {
|
|
111
|
+
shippedSkillsDir?: string | null;
|
|
112
|
+
reportFile?: string;
|
|
113
|
+
}): MeasureReport;
|
|
114
|
+
export declare function measureMarkdown(r: MeasureReport): string;
|
|
115
|
+
/** A side-by-side table of several reports (a cross-application comparison). */
|
|
116
|
+
export declare function compareMarkdown(reports: MeasureReport[]): string;
|
|
117
|
+
export declare function relativeTo(projectDir: string, file: string): string;
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `feltkit measure`: what an application's repository is made of, measured from the repository.
|
|
3
|
+
*
|
|
4
|
+
* Every file gets exactly one class and the basis for it, so a number can always be traced back to the
|
|
5
|
+
* files that produced it. Classification takes the strongest evidence available, in this order:
|
|
6
|
+
*
|
|
7
|
+
* 1. a declaration in feltkit.measure.json (with a reason),
|
|
8
|
+
* 2. provenance: the codegen header and a regeneration comparison; feltkit.scaffold.json hashes;
|
|
9
|
+
* the marker `feltkit skills` writes,
|
|
10
|
+
* 3. path conventions of a FeltKit project.
|
|
11
|
+
*
|
|
12
|
+
* Nothing here loads or runs the application, uses the network, or estimates. Platform consumption and
|
|
13
|
+
* infrastructure findings are static call-site evidence, and are labelled as such: a finding is a
|
|
14
|
+
* candidate for review, not a verdict. The report is deterministic (no timestamps), so it can be
|
|
15
|
+
* committed and checked in CI, and its history is the trend.
|
|
16
|
+
*/
|
|
17
|
+
import { execFileSync } from "node:child_process";
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
20
|
+
import { extname, join, relative, sep } from "node:path";
|
|
21
|
+
import { FeltKitError } from "../errors.js";
|
|
22
|
+
import { codegenContent } from "../server/project.js";
|
|
23
|
+
export const MEASURE_SCHEMA = "feltkit.measure/1";
|
|
24
|
+
export const MEASURE_CONFIG = "feltkit.measure.json";
|
|
25
|
+
export const SCAFFOLD_MANIFEST = "feltkit.scaffold.json";
|
|
26
|
+
const GENERATED_API = "feltkit/_generated/api.ts";
|
|
27
|
+
const SKILL_MARKER = ".feltkit-skill.json";
|
|
28
|
+
/** The classes. `excluded` is counted but is not code (docs, images, lockfiles). */
|
|
29
|
+
export const CLASSES = [
|
|
30
|
+
"domain",
|
|
31
|
+
"experience",
|
|
32
|
+
"infrastructure",
|
|
33
|
+
"generated",
|
|
34
|
+
"configuration",
|
|
35
|
+
"tests",
|
|
36
|
+
"third-party",
|
|
37
|
+
"platform",
|
|
38
|
+
"excluded",
|
|
39
|
+
"unclassified",
|
|
40
|
+
];
|
|
41
|
+
export const CLASS_MEANING = {
|
|
42
|
+
domain: "Server code that expresses the application: collections, rules, queries, mutations, actions (feltkit/).",
|
|
43
|
+
experience: "What people see and use: UI, styles, HTML, browser extension.",
|
|
44
|
+
infrastructure: "Plumbing the application wrote for itself: scripts, servers, adapters, app-built audit or queues.",
|
|
45
|
+
generated: "Written by a tool and unchanged: codegen output, or scaffolded files still identical to the template.",
|
|
46
|
+
configuration: "Build, package, deployment and tool configuration.",
|
|
47
|
+
tests: "Tests, fixtures and acceptance scripts.",
|
|
48
|
+
"third-party": "Code vendored from another project.",
|
|
49
|
+
platform: "Files the platform installs and keeps current (FeltKit Agent Skills).",
|
|
50
|
+
excluded: "Not code: documentation, images, fonts, lockfiles, licences.",
|
|
51
|
+
unclassified: "No rule applies. Declare it in feltkit.measure.json.",
|
|
52
|
+
};
|
|
53
|
+
/** Classes the application's own team writes and maintains (tests are reported beside them). */
|
|
54
|
+
export const AUTHORED = ["domain", "experience", "infrastructure", "configuration"];
|
|
55
|
+
// ---------------------------------------------------------------------------------------------------
|
|
56
|
+
// Files and lines
|
|
57
|
+
const ALWAYS_SKIPPED = new Set(["node_modules", ".git", "dist", ".feltkit", "coverage", ".turbo", ".next"]);
|
|
58
|
+
/** The files the repository is made of: tracked plus untracked-not-ignored (git), or a walk. */
|
|
59
|
+
export function projectFiles(projectDir) {
|
|
60
|
+
try {
|
|
61
|
+
const out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 });
|
|
62
|
+
const files = out.split("\0").filter(Boolean).filter((f) => existsSync(join(projectDir, f)) && !f.split("/").some((s) => ALWAYS_SKIPPED.has(s)));
|
|
63
|
+
if (files.length)
|
|
64
|
+
return [...new Set(files)].sort();
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Not a git repository (or git is missing): walk instead.
|
|
68
|
+
}
|
|
69
|
+
const out = [];
|
|
70
|
+
const walk = (dir) => {
|
|
71
|
+
for (const name of readdirSync(join(projectDir, dir))) {
|
|
72
|
+
if (ALWAYS_SKIPPED.has(name))
|
|
73
|
+
continue;
|
|
74
|
+
const rel = dir ? `${dir}/${name}` : name;
|
|
75
|
+
if (statSync(join(projectDir, rel)).isDirectory())
|
|
76
|
+
walk(rel);
|
|
77
|
+
else
|
|
78
|
+
out.push(rel);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
walk("");
|
|
82
|
+
return out.sort();
|
|
83
|
+
}
|
|
84
|
+
const CODE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".css", ".scss", ".html", ".vue", ".svelte", ".sql", ".sh", ".py", ".rs", ".go"]);
|
|
85
|
+
const DATA = new Set([".json", ".jsonc", ".yml", ".yaml", ".toml"]);
|
|
86
|
+
/** Lines that are code: not blank and not only a comment. JSON/YAML/TOML count non-blank lines. */
|
|
87
|
+
export function codeLines(path, text) {
|
|
88
|
+
const ext = extname(path).toLowerCase();
|
|
89
|
+
const isDockerfile = /(^|\/)Dockerfile[^/]*$/.test(path);
|
|
90
|
+
if (!CODE.has(ext) && !DATA.has(ext) && !isDockerfile)
|
|
91
|
+
return 0;
|
|
92
|
+
const hashComments = [".yml", ".yaml", ".toml", ".sh", ".py"].includes(ext) || isDockerfile;
|
|
93
|
+
let n = 0;
|
|
94
|
+
let inBlock = false;
|
|
95
|
+
for (const raw of text.split("\n")) {
|
|
96
|
+
const line = raw.trim();
|
|
97
|
+
if (inBlock) {
|
|
98
|
+
if (line.includes("*/") || line.includes("-->"))
|
|
99
|
+
inBlock = false;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (!line)
|
|
103
|
+
continue;
|
|
104
|
+
if (hashComments && line.startsWith("#"))
|
|
105
|
+
continue;
|
|
106
|
+
if (line.startsWith("//"))
|
|
107
|
+
continue;
|
|
108
|
+
if (line.startsWith("/*") || line.startsWith("{/*") || line.startsWith("<!--")) {
|
|
109
|
+
if (!line.includes("*/") && !line.includes("-->"))
|
|
110
|
+
inBlock = true;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (line.startsWith("*") && !DATA.has(ext))
|
|
114
|
+
continue;
|
|
115
|
+
n += 1;
|
|
116
|
+
}
|
|
117
|
+
return n;
|
|
118
|
+
}
|
|
119
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
120
|
+
/** `*` matches within a path segment, `**` across segments. */
|
|
121
|
+
export function globToRegExp(glob) {
|
|
122
|
+
let re = "";
|
|
123
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
124
|
+
const ch = glob[i];
|
|
125
|
+
if (ch === "*" && glob[i + 1] === "*") {
|
|
126
|
+
re += glob[i + 2] === "/" ? "(?:.*/)?" : ".*";
|
|
127
|
+
i += glob[i + 2] === "/" ? 2 : 1;
|
|
128
|
+
}
|
|
129
|
+
else if (ch === "*")
|
|
130
|
+
re += "[^/]*";
|
|
131
|
+
else if (ch === "?")
|
|
132
|
+
re += "[^/]";
|
|
133
|
+
else
|
|
134
|
+
re += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
135
|
+
}
|
|
136
|
+
// A directory path declares everything under it.
|
|
137
|
+
return new RegExp(`^${re}(?:/.*)?$`);
|
|
138
|
+
}
|
|
139
|
+
// ---------------------------------------------------------------------------------------------------
|
|
140
|
+
// Classification by convention
|
|
141
|
+
const ASSET = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf", ".mp4", ".webm", ".mp3", ".wav", ".pdf", ".zip", ".tgz"]);
|
|
142
|
+
const LOCKFILES = new Set(["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "Cargo.lock", "npm-shrinkwrap.json"]);
|
|
143
|
+
const CONFIG_FILES = /^(package\.json|tsconfig[^/]*\.json|jsconfig\.json|vite[^/]*\.config\.[cm]?[jt]s|vitest[^/]*\.config\.[cm]?[jt]s|playwright[^/]*\.config\.[cm]?[jt]s|eslint[^/]*|\.eslintrc[^/]*|\.prettierrc[^/]*|prettier\.config\.[cm]?js|Dockerfile[^/]*|docker-compose[^/]*\.ya?ml|fly\.toml|vercel\.json|wrangler\.toml|netlify\.toml|feltdb\.contract\.json|feltkit\.measure\.json|feltkit\.scaffold\.json|\.env\.example|\.npmrc|\.nvmrc|\.node-version|\.editorconfig|\.gitignore|\.gitattributes|\.dockerignore)$/;
|
|
144
|
+
function conventionClass(path) {
|
|
145
|
+
const base = path.split("/").pop();
|
|
146
|
+
const ext = extname(path).toLowerCase();
|
|
147
|
+
const top = path.split("/")[0];
|
|
148
|
+
if (LOCKFILES.has(base))
|
|
149
|
+
return { class: "excluded", basis: "lockfile" };
|
|
150
|
+
if (/^(LICEN[CS]E|COPYING|NOTICE)(\.[a-z]+)?$/i.test(base))
|
|
151
|
+
return { class: "excluded", basis: "licence" };
|
|
152
|
+
if (ext === ".md" || ext === ".mdx" || ext === ".txt" || top === "docs")
|
|
153
|
+
return { class: "excluded", basis: "documentation" };
|
|
154
|
+
if (ASSET.has(ext))
|
|
155
|
+
return { class: "excluded", basis: "asset" };
|
|
156
|
+
if (["vendor", "third_party", "third-party"].includes(top))
|
|
157
|
+
return { class: "third-party", basis: `path: ${top}/` };
|
|
158
|
+
if (["tests", "test", "e2e", "__tests__", "spec"].includes(top) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(base) || path.includes("/__tests__/"))
|
|
159
|
+
return { class: "tests", basis: "path: tests" };
|
|
160
|
+
if (top === ".github" || top === ".vscode" || top === ".devcontainer" || CONFIG_FILES.test(base) && !path.startsWith("feltkit/"))
|
|
161
|
+
return { class: "configuration", basis: "configuration file" };
|
|
162
|
+
if (top === "feltkit")
|
|
163
|
+
return CODE.has(ext) ? { class: "domain", basis: "path: feltkit/ (server functions)" } : { class: "configuration", basis: "path: feltkit/ (non-code)" };
|
|
164
|
+
if (["src", "public", "extension", "app", "pages", "components", "styles"].includes(top) || ext === ".html" || ext === ".css") {
|
|
165
|
+
return CODE.has(ext) || DATA.has(ext) ? { class: "experience", basis: `path: ${top === path ? "root" : `${top}/`} (UI)` } : { class: "excluded", basis: "asset" };
|
|
166
|
+
}
|
|
167
|
+
if (["scripts", "server", "bin", "tools", "infra", "deploy", "ops"].includes(top))
|
|
168
|
+
return { class: "infrastructure", basis: `path: ${top}/ (app tooling)` };
|
|
169
|
+
if (top === ".claude")
|
|
170
|
+
return { class: "configuration", basis: "agent configuration" };
|
|
171
|
+
return { class: "unclassified", basis: "no rule" };
|
|
172
|
+
}
|
|
173
|
+
const DETECTORS = [
|
|
174
|
+
{ id: "http-server", title: "App-built HTTP server", in: ["domain", "infrastructure", "experience"], pattern: /from\s+["'](express|fastify|koa|hono)["']|\bcreateServer\s*\(/, platform: "FeltKit serves every function over HTTP with authorization (app.query/mutation/action)" },
|
|
175
|
+
{ id: "realtime-server", title: "App-built realtime transport", in: ["domain", "infrastructure"], pattern: /new\s+WebSocketServer\b|["']text\/event-stream["']/, platform: "Live queries (useQuery) and streaming actions (app.action + useAction)" },
|
|
176
|
+
{ id: "queue-or-scheduler", title: "App-built queue or scheduler", in: ["domain", "infrastructure"], pattern: /from\s+["'](bullmq|bull|bee-queue|node-cron|cron|agenda|bree|node-schedule)["']|\bsetInterval\s*\(/, platform: "ctx.afterCommit.jobs.enqueue and operator-managed schedules" },
|
|
177
|
+
{ id: "model-sdk", title: "Direct model-provider SDK", in: ["domain", "infrastructure", "experience"], pattern: /from\s+["'](openai|@anthropic-ai\/[\w-]+|ai|@google\/generative-ai|cohere-ai|ollama)["']/, platform: "ctx.model (generate, stream, status), provider chosen by configuration" },
|
|
178
|
+
{ id: "auth-library", title: "App-built authentication", in: ["domain", "infrastructure", "experience"], pattern: /from\s+["'](bcrypt|bcryptjs|argon2|jsonwebtoken|jose|passport[\w-]*|express-session)["']/, platform: "FeltKit accounts, sessions and roles (ctx.auth, auth: { accounts })" },
|
|
179
|
+
{ id: "hand-rolled-api-client", title: "Hand-written calls to the app's own API", in: ["experience"], pattern: /\bfetch\(\s*[`"']\/api\//, platform: "The generated api references with useQuery/useMutation/useAction" },
|
|
180
|
+
{ id: "sql", title: "SQL or migrations", in: ["domain", "infrastructure"], pattern: /^\s*(CREATE|ALTER)\s+TABLE\b/im, platform: "Collections with schemas and FeltKit's schema lifecycle" },
|
|
181
|
+
{ id: "audit-trail", title: "App-built business audit trail", in: ["domain"], pattern: /app\.collection\(\s*["'](audit|auditLog|audit_log|events|activity|actions|history)["']/, platform: "app.auditTrail (events written in the change's transaction, ordered per subject by a FeltDB sequence)" },
|
|
182
|
+
{ id: "counter-collection", title: "App-built counter or sequence", in: ["domain"], pattern: /app\.collection\(\s*["'](counters?|sequences?|ids)["']/, platform: "ctx.db.sequence" },
|
|
183
|
+
];
|
|
184
|
+
function lineOf(text, index) {
|
|
185
|
+
let n = 1;
|
|
186
|
+
for (let i = 0; i < index; i += 1)
|
|
187
|
+
if (text.charCodeAt(i) === 10)
|
|
188
|
+
n += 1;
|
|
189
|
+
return n;
|
|
190
|
+
}
|
|
191
|
+
// ---------------------------------------------------------------------------------------------------
|
|
192
|
+
function readConfig(projectDir) {
|
|
193
|
+
const file = join(projectDir, MEASURE_CONFIG);
|
|
194
|
+
if (!existsSync(file))
|
|
195
|
+
return {};
|
|
196
|
+
try {
|
|
197
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
throw new FeltKitError("CONFIGURATION", `${MEASURE_CONFIG} is not valid JSON: ${error.message}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function readJson(file) {
|
|
204
|
+
try {
|
|
205
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Measure the application at projectDir. `shippedSkills` is the platform's current skill set, if known. */
|
|
212
|
+
export function measure(projectDir, options = {}) {
|
|
213
|
+
const config = readConfig(projectDir);
|
|
214
|
+
const checks = [];
|
|
215
|
+
// The kept report is this command's output, not part of what it measures.
|
|
216
|
+
const reportFile = (options.reportFile ?? config.report)?.replace(/^\.\//, "");
|
|
217
|
+
const all = projectFiles(projectDir).filter((f) => f !== reportFile);
|
|
218
|
+
const text = new Map();
|
|
219
|
+
const read = (p) => {
|
|
220
|
+
let b = text.get(p);
|
|
221
|
+
if (!b)
|
|
222
|
+
text.set(p, (b = readFileSync(join(projectDir, p))));
|
|
223
|
+
return b;
|
|
224
|
+
};
|
|
225
|
+
// Declarations, each of which must still match something.
|
|
226
|
+
const declarations = (config.classify ?? []).map((d) => ({ ...d, re: globToRegExp(d.path), used: false }));
|
|
227
|
+
for (const d of declarations) {
|
|
228
|
+
if (!CLASSES.includes(d.class))
|
|
229
|
+
throw new FeltKitError("CONFIGURATION", `${MEASURE_CONFIG}: "${d.class}" is not a class.`, { hint: `Use one of: ${CLASSES.join(", ")}.` });
|
|
230
|
+
if (!d.reason?.trim())
|
|
231
|
+
throw new FeltKitError("CONFIGURATION", `${MEASURE_CONFIG}: the declaration for "${d.path}" has no reason.`, { hint: "Every declared classification says why, so the number can be reviewed." });
|
|
232
|
+
}
|
|
233
|
+
// Scaffold provenance.
|
|
234
|
+
const manifestPath = config.scaffold ?? SCAFFOLD_MANIFEST;
|
|
235
|
+
const manifest = existsSync(join(projectDir, manifestPath)) ? readJson(join(projectDir, manifestPath)) : null;
|
|
236
|
+
if (manifest && manifest.schema !== "feltkit.scaffold/1")
|
|
237
|
+
throw new FeltKitError("CONFIGURATION", `${manifestPath} is not a feltkit.scaffold/1 manifest.`);
|
|
238
|
+
const scaffoldFiles = manifest?.files ?? {};
|
|
239
|
+
// Skill provenance.
|
|
240
|
+
const skills = [];
|
|
241
|
+
const skillDirs = new Set(all.filter((f) => f.startsWith(".claude/skills/")).map((f) => f.split("/")[2]));
|
|
242
|
+
const shipped = options.shippedSkillsDir && existsSync(options.shippedSkillsDir) ? new Set(readdirSync(options.shippedSkillsDir)) : null;
|
|
243
|
+
const platformSkills = new Set();
|
|
244
|
+
for (const name of [...skillDirs].sort()) {
|
|
245
|
+
const marker = readJson(join(projectDir, ".claude/skills", name, SKILL_MARKER));
|
|
246
|
+
const isPlatform = Boolean(marker) || (shipped?.has(name) ?? name.startsWith("feltkit-"));
|
|
247
|
+
if (!isPlatform)
|
|
248
|
+
continue;
|
|
249
|
+
platformSkills.add(name);
|
|
250
|
+
let current = null;
|
|
251
|
+
if (shipped?.has(name)) {
|
|
252
|
+
const ours = join(options.shippedSkillsDir, name, "SKILL.md");
|
|
253
|
+
const theirs = join(projectDir, ".claude/skills", name, "SKILL.md");
|
|
254
|
+
current = existsSync(ours) && existsSync(theirs) ? sha256(readFileSync(ours)) === sha256(readFileSync(theirs)) : false;
|
|
255
|
+
}
|
|
256
|
+
skills.push({ name, installedBy: marker?.version ? `feltkit skills ${marker.version}` : null, current });
|
|
257
|
+
}
|
|
258
|
+
const staleSkills = skills.filter((s) => s.current === false).map((s) => s.name);
|
|
259
|
+
if (skills.length) {
|
|
260
|
+
checks.push({
|
|
261
|
+
name: "platform skills current",
|
|
262
|
+
ok: staleSkills.length === 0,
|
|
263
|
+
detail: staleSkills.length ? `${staleSkills.join(", ")} differ from the skills shipped with the installed FeltKit` : `${skills.length} skill(s) ${shipped ? "match the installed FeltKit" : "(installed FeltKit not found; not compared)"}`,
|
|
264
|
+
fix: "npx feltkit skills install",
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
// Generated code: compare with what codegen writes now.
|
|
268
|
+
let generated = null;
|
|
269
|
+
if (existsSync(join(projectDir, "feltkit"))) {
|
|
270
|
+
const exists = all.includes(GENERATED_API);
|
|
271
|
+
const current = exists && read(GENERATED_API).toString("utf8") === codegenContent(projectDir);
|
|
272
|
+
generated = { file: GENERATED_API, current };
|
|
273
|
+
checks.push({
|
|
274
|
+
name: "generated code current",
|
|
275
|
+
ok: current || !exists,
|
|
276
|
+
detail: !exists ? `${GENERATED_API} is not committed (it is written by feltkit dev / codegen)` : current ? `${GENERATED_API} matches what codegen writes` : `${GENERATED_API} differs from what codegen writes: edited by hand, or stale`,
|
|
277
|
+
fix: "npx feltkit codegen",
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
// Classify.
|
|
281
|
+
let unmodified = 0;
|
|
282
|
+
let modified = 0;
|
|
283
|
+
const files = [];
|
|
284
|
+
for (const path of all) {
|
|
285
|
+
const buf = read(path);
|
|
286
|
+
const lines = codeLines(path, buf.toString("utf8"));
|
|
287
|
+
const scaffoldHash = scaffoldFiles[path];
|
|
288
|
+
const scaffold = scaffoldHash ? (sha256(buf) === scaffoldHash ? "unmodified" : "modified") : undefined;
|
|
289
|
+
if (scaffold === "unmodified")
|
|
290
|
+
unmodified += 1;
|
|
291
|
+
if (scaffold === "modified")
|
|
292
|
+
modified += 1;
|
|
293
|
+
const declared = declarations.find((d) => d.re.test(path));
|
|
294
|
+
let cls;
|
|
295
|
+
if (declared) {
|
|
296
|
+
declared.used = true;
|
|
297
|
+
cls = { class: declared.class, basis: `declared: ${declared.reason}` };
|
|
298
|
+
}
|
|
299
|
+
else if (path === GENERATED_API)
|
|
300
|
+
cls = { class: "generated", basis: generated?.current ? "codegen (matches regeneration)" : "codegen (differs from regeneration)" };
|
|
301
|
+
else if (path.startsWith("feltkit/_generated/"))
|
|
302
|
+
cls = { class: "generated", basis: "path: feltkit/_generated/" };
|
|
303
|
+
else if (path.startsWith(".claude/skills/") && platformSkills.has(path.split("/")[2]))
|
|
304
|
+
cls = { class: "platform", basis: "FeltKit Agent Skill" };
|
|
305
|
+
else if (scaffold === "unmodified" && conventionClass(path).class !== "excluded")
|
|
306
|
+
cls = { class: "generated", basis: `scaffold (${manifest.generator} ${manifest.version}, unmodified)` };
|
|
307
|
+
else
|
|
308
|
+
cls = conventionClass(path);
|
|
309
|
+
files.push({ path, ...cls, lines, ...(scaffold ? { scaffold } : {}) });
|
|
310
|
+
}
|
|
311
|
+
const missing = Object.keys(scaffoldFiles).filter((p) => !all.includes(p)).length;
|
|
312
|
+
const unused = declarations.filter((d) => !d.used);
|
|
313
|
+
checks.push({
|
|
314
|
+
name: "declarations match files",
|
|
315
|
+
ok: unused.length === 0,
|
|
316
|
+
detail: unused.length ? `${unused.map((d) => d.path).join(", ")} match no file` : `${declarations.length} declaration(s), each matches a file`,
|
|
317
|
+
fix: `Remove or correct the stale entries in ${MEASURE_CONFIG}.`,
|
|
318
|
+
});
|
|
319
|
+
const unclassified = files.filter((f) => f.class === "unclassified" && f.lines > 0);
|
|
320
|
+
checks.push({
|
|
321
|
+
name: "every code file classified",
|
|
322
|
+
ok: unclassified.length === 0,
|
|
323
|
+
detail: unclassified.length ? `${unclassified.length} code file(s) match no rule: ${unclassified.slice(0, 5).map((f) => f.path).join(", ")}${unclassified.length > 5 ? ", …" : ""}` : "every file with code has a class",
|
|
324
|
+
fix: `Declare them in ${MEASURE_CONFIG} with a class and a reason.`,
|
|
325
|
+
});
|
|
326
|
+
const totals = Object.fromEntries(CLASSES.map((c) => [c, { files: 0, lines: 0 }]));
|
|
327
|
+
for (const f of files) {
|
|
328
|
+
totals[f.class].files += 1;
|
|
329
|
+
totals[f.class].lines += f.lines;
|
|
330
|
+
}
|
|
331
|
+
const authored = AUTHORED.reduce((acc, c) => ({ files: acc.files + totals[c].files, lines: acc.lines + totals[c].lines }), { files: 0, lines: 0 });
|
|
332
|
+
// Definitions (static: app.<method>( call sites in the server code) and collection names. Every
|
|
333
|
+
// server module counts, whoever wrote it: a scaffolded module the app still serves is still defined.
|
|
334
|
+
const server = files.filter((f) => f.path.startsWith("feltkit/") && !f.path.startsWith("feltkit/_generated/") && /\.[cm]?[jt]sx?$/.test(f.path) && !["tests", "third-party", "excluded"].includes(f.class));
|
|
335
|
+
const serverText = server.map((f) => read(f.path).toString("utf8")).join("\n");
|
|
336
|
+
const defs = {};
|
|
337
|
+
for (const m of serverText.matchAll(/\bapp\.([a-zA-Z]+)\(/g))
|
|
338
|
+
defs[m[1]] = (defs[m[1]] ?? 0) + 1;
|
|
339
|
+
const collections = [...serverText.matchAll(/\bapp\.collection\(\s*["']([^"']+)["']/g)].map((m) => m[1]);
|
|
340
|
+
// Platform consumption: ctx.<area>[.<sub>] and named imports from @feltdb/feltkit, in authored + test code.
|
|
341
|
+
const consuming = files.filter((f) => [...AUTHORED, "tests"].includes(f.class) && /\.[cm]?[jt]sx?$/.test(f.path));
|
|
342
|
+
const usage = new Map();
|
|
343
|
+
const note = (api, file) => {
|
|
344
|
+
const u = usage.get(api) ?? { callSites: 0, files: new Set() };
|
|
345
|
+
u.callSites += 1;
|
|
346
|
+
u.files.add(file);
|
|
347
|
+
usage.set(api, u);
|
|
348
|
+
};
|
|
349
|
+
for (const f of consuming) {
|
|
350
|
+
const src = read(f.path).toString("utf8");
|
|
351
|
+
// `ctx` is FeltKit's function context only in server code; elsewhere (Playwright, canvas) it is not.
|
|
352
|
+
if (f.path.startsWith("feltkit/")) {
|
|
353
|
+
for (const m of src.matchAll(/\bctx\.(afterCommit|services)\.([a-zA-Z]+)/g))
|
|
354
|
+
note(`ctx.${m[1]}.${m[2]}`, f.path);
|
|
355
|
+
for (const m of src.matchAll(/\bctx\.(?!afterCommit\b|services\b)([a-zA-Z]+)\b/g))
|
|
356
|
+
note(`ctx.${m[1]}`, f.path);
|
|
357
|
+
}
|
|
358
|
+
for (const m of src.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*["'](@feltdb\/feltkit(?:\/[a-z]+)?)["']/g)) {
|
|
359
|
+
for (const raw of m[1].split(",")) {
|
|
360
|
+
const name = raw.trim().replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim();
|
|
361
|
+
if (!name)
|
|
362
|
+
continue;
|
|
363
|
+
// Count uses of the imported name in the file, not the import itself. A short name (the schema
|
|
364
|
+
// builder `s`) counts only where it is used as one (`s.string()`), not every word "s".
|
|
365
|
+
const id = name.replace(/\$/g, "\\$");
|
|
366
|
+
const pattern = name.length <= 2 ? `(?<![\\w.'])${id}\\.(?=[a-zA-Z])` : `\\b${id}\\b`;
|
|
367
|
+
const uses = (src.match(new RegExp(pattern, "g")) ?? []).length - (name.length <= 2 ? 0 : 1);
|
|
368
|
+
for (let i = 0; i < Math.max(uses, 1); i += 1)
|
|
369
|
+
note(`${m[2]} ${name}`, f.path);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const consumption = [...usage.entries()].map(([api, u]) => ({ api, callSites: u.callSites, files: u.files.size })).sort((a, b) => b.callSites - a.callSites || a.api.localeCompare(b.api));
|
|
374
|
+
// Infrastructure findings.
|
|
375
|
+
const findings = [];
|
|
376
|
+
for (const f of files) {
|
|
377
|
+
if (!/\.[cm]?[jt]sx?$|\.sql$/.test(f.path))
|
|
378
|
+
continue;
|
|
379
|
+
const detectors = DETECTORS.filter((d) => d.in.includes(f.class));
|
|
380
|
+
if (!detectors.length)
|
|
381
|
+
continue;
|
|
382
|
+
const src = read(f.path).toString("utf8");
|
|
383
|
+
for (const d of detectors) {
|
|
384
|
+
const flags = d.pattern.flags.includes("g") ? d.pattern.flags : `${d.pattern.flags}g`;
|
|
385
|
+
for (const m of src.matchAll(new RegExp(d.pattern.source, flags))) {
|
|
386
|
+
const line = lineOf(src, m.index ?? 0);
|
|
387
|
+
const key = `${d.id}:${f.path}`;
|
|
388
|
+
findings.push({ id: d.id, title: d.title, file: f.path, line, evidence: (src.split("\n")[line - 1] ?? "").trim().slice(0, 160), platform: d.platform, ...(config.acknowledged?.[key] ? { acknowledged: config.acknowledged[key] } : {}) });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
findings.sort((a, b) => a.id.localeCompare(b.id) || a.file.localeCompare(b.file) || a.line - b.line);
|
|
393
|
+
if (config.acknowledged) {
|
|
394
|
+
const live = new Set(findings.map((f) => `${f.id}:${f.file}`));
|
|
395
|
+
const stale = Object.keys(config.acknowledged).filter((k) => !live.has(k));
|
|
396
|
+
checks.push({
|
|
397
|
+
name: "acknowledged findings still exist",
|
|
398
|
+
ok: stale.length === 0,
|
|
399
|
+
detail: stale.length ? `${stale.join(", ")} no longer found` : `${Object.keys(config.acknowledged).length} acknowledged finding(s), each still present`,
|
|
400
|
+
fix: `Remove the resolved entries from "acknowledged" in ${MEASURE_CONFIG}.`,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
const pkg = readJson(join(projectDir, "package.json"));
|
|
404
|
+
const installed = readJson(join(projectDir, "node_modules/@feltdb/feltkit/package.json"));
|
|
405
|
+
return {
|
|
406
|
+
schema: MEASURE_SCHEMA,
|
|
407
|
+
app: { name: pkg?.name ?? null, feltkit: pkg?.dependencies?.["@feltdb/feltkit"] ?? pkg?.devDependencies?.["@feltdb/feltkit"] ?? null, installed: installed?.version ?? null },
|
|
408
|
+
method: {
|
|
409
|
+
files: "git ls-files (tracked, and untracked files that are not ignored); node_modules, dist, .feltkit and .git are never counted",
|
|
410
|
+
lines: "lines that are not blank and not only a comment; JSON/YAML/TOML count non-blank lines; assets and documentation count 0",
|
|
411
|
+
consumption: "static call sites of ctx.* and of names imported from @feltdb/feltkit, in authored code and tests",
|
|
412
|
+
findings: "static patterns in authored code; a finding is a candidate for review, not a verdict",
|
|
413
|
+
},
|
|
414
|
+
provenance: {
|
|
415
|
+
scaffold: manifest ? { manifest: manifestPath, generator: manifest.generator, version: manifest.version, template: manifest.template, files: Object.keys(scaffoldFiles).length, unmodified, modified, missing } : null,
|
|
416
|
+
generated,
|
|
417
|
+
skills,
|
|
418
|
+
},
|
|
419
|
+
totals,
|
|
420
|
+
authored,
|
|
421
|
+
definitions: { app: Object.fromEntries(Object.entries(defs).sort(([a], [b]) => a.localeCompare(b))), collections },
|
|
422
|
+
consumption,
|
|
423
|
+
findings,
|
|
424
|
+
checks,
|
|
425
|
+
files,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
// ---------------------------------------------------------------------------------------------------
|
|
429
|
+
// Output
|
|
430
|
+
const table = (head, rows, align) => [`| ${head.join(" | ")} |`, `|${(align ?? head.map(() => "---")).join("|")}|`, ...rows.map((r) => `| ${r.join(" | ")} |`)].join("\n");
|
|
431
|
+
export function measureMarkdown(r) {
|
|
432
|
+
const shown = CLASSES.filter((c) => r.totals[c].files > 0);
|
|
433
|
+
const parts = [];
|
|
434
|
+
parts.push(`## ${r.app.name ?? "Application"}: what the repository is made of`);
|
|
435
|
+
parts.push(`Measured by \`feltkit measure\` (${MEASURE_SCHEMA}). FeltKit ${r.app.feltkit ?? "not a dependency"}${r.app.installed ? ` (installed ${r.app.installed})` : ""}.`);
|
|
436
|
+
parts.push(table(["Class", "Files", "Lines of code", "Meaning"], shown.map((c) => [c, r.totals[c].files, r.totals[c].lines, CLASS_MEANING[c]]), ["---", "--:", "--:", "---"]));
|
|
437
|
+
parts.push(`**Authored by the application** (${AUTHORED.join(" + ")}): ${r.authored.lines} lines in ${r.authored.files} files. Tests: ${r.totals.tests.lines} lines.`);
|
|
438
|
+
const s = r.provenance.scaffold;
|
|
439
|
+
parts.push(`**Provenance.** ${s ? `Scaffolded by ${s.generator} ${s.version} (${s.template}): ${s.files} files, ${s.unmodified} unchanged, ${s.modified} changed, ${s.missing} removed.` : "No scaffold manifest, so scaffolded files cannot be told from written ones; they are counted by path."} ${r.provenance.generated ? `Generated API: ${r.provenance.generated.current ? "matches regeneration" : "**differs from regeneration**"}.` : ""}${r.provenance.skills.length ? ` Platform skills: ${r.provenance.skills.map((k) => `${k.name}${k.current === false ? " (stale)" : ""}`).join(", ")}.` : ""}`);
|
|
440
|
+
const defs = Object.entries(r.definitions.app).map(([k, v]) => `${v} ${k}`).join(", ");
|
|
441
|
+
parts.push(`**Definitions** (\`app.*\` in feltkit/): ${defs || "none"}. Collections: ${r.definitions.collections.join(", ") || "none"}.`);
|
|
442
|
+
if (r.consumption.length)
|
|
443
|
+
parts.push(`### Platform consumption (static call sites)\n\n${table(["API", "Call sites", "Files"], r.consumption.map((u) => [`\`${u.api}\``, u.callSites, u.files]), ["---", "--:", "--:"])}`);
|
|
444
|
+
if (r.findings.length) {
|
|
445
|
+
parts.push(`### Infrastructure findings (candidates for review)\n\n${table(["Finding", "Where", "Evidence", "Platform alternative"], r.findings.map((f) => [`${f.title}${f.acknowledged ? ` (acknowledged: ${f.acknowledged})` : ""}`, `\`${f.file}:${f.line}\``, `\`${f.evidence.replace(/\|/g, "\\|").replace(/`/g, "'")}\``, f.platform ?? "**none yet: a platform gap candidate**"]))}`);
|
|
446
|
+
}
|
|
447
|
+
else
|
|
448
|
+
parts.push("### Infrastructure findings\n\nNone.");
|
|
449
|
+
parts.push(`### Checks\n\n${r.checks.map((c) => `- ${c.ok ? "✓" : "✗"} ${c.name}: ${c.detail}${!c.ok && c.fix ? ` (fix: ${c.fix})` : ""}`).join("\n")}`);
|
|
450
|
+
return `${parts.join("\n\n")}\n`;
|
|
451
|
+
}
|
|
452
|
+
/** A side-by-side table of several reports (a cross-application comparison). */
|
|
453
|
+
export function compareMarkdown(reports) {
|
|
454
|
+
const name = (r) => r.app.name ?? "app";
|
|
455
|
+
const rows = [];
|
|
456
|
+
for (const c of CLASSES) {
|
|
457
|
+
if (reports.every((r) => r.totals[c].files === 0))
|
|
458
|
+
continue;
|
|
459
|
+
rows.push([c, ...reports.map((r) => `${r.totals[c].lines} (${r.totals[c].files})`)]);
|
|
460
|
+
}
|
|
461
|
+
rows.push(["**authored**", ...reports.map((r) => `**${r.authored.lines}** (${r.authored.files})`)]);
|
|
462
|
+
const share = (r, c) => (r.authored.lines ? `${Math.round((100 * r.totals[c].lines) / r.authored.lines)}%` : "–");
|
|
463
|
+
rows.push(["domain share of authored", ...reports.map((r) => share(r, "domain"))]);
|
|
464
|
+
rows.push(["infrastructure share of authored", ...reports.map((r) => share(r, "infrastructure"))]);
|
|
465
|
+
rows.push(["collections", ...reports.map((r) => r.definitions.collections.length)]);
|
|
466
|
+
for (const k of ["query", "mutation", "action", "agent"])
|
|
467
|
+
rows.push([`app.${k}`, ...reports.map((r) => r.definitions.app[k] ?? 0)]);
|
|
468
|
+
rows.push(["distinct platform APIs used", ...reports.map((r) => r.consumption.length)]);
|
|
469
|
+
rows.push(["infrastructure findings", ...reports.map((r) => r.findings.length)]);
|
|
470
|
+
rows.push(["platform-gap candidates", ...reports.map((r) => r.findings.filter((f) => f.platform === null).length)]);
|
|
471
|
+
rows.push(["scaffold provenance", ...reports.map((r) => (r.provenance.scaffold ? `${r.provenance.scaffold.version}: ${r.provenance.scaffold.unmodified}/${r.provenance.scaffold.files} unchanged` : "none"))]);
|
|
472
|
+
rows.push(["FeltKit", ...reports.map((r) => r.app.feltkit ?? "–")]);
|
|
473
|
+
rows.push(["failing checks", ...reports.map((r) => r.checks.filter((c) => !c.ok).map((c) => c.name).join("; ") || "none")]);
|
|
474
|
+
return `${table(["Lines (files)", ...reports.map(name)], rows, ["---", ...reports.map(() => "--:")])}\n`;
|
|
475
|
+
}
|
|
476
|
+
export function relativeTo(projectDir, file) {
|
|
477
|
+
return relative(projectDir, file).split(sep).join("/");
|
|
478
|
+
}
|
|
479
|
+
//# sourceMappingURL=index.js.map
|