@autotelic/joggle 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/JOGGLE.md +634 -0
  2. package/LICENSE +21 -0
  3. package/README.md +88 -2
  4. package/bin/joggle.js +6 -0
  5. package/dist/answer-store.js +305 -0
  6. package/dist/architecture.js +190 -0
  7. package/dist/ask.js +184 -0
  8. package/dist/astro.js +75 -0
  9. package/dist/atoms.js +76 -0
  10. package/dist/bundles.js +156 -0
  11. package/dist/calibration.js +60 -0
  12. package/dist/candidates.js +561 -0
  13. package/dist/canonical.js +24 -0
  14. package/dist/cascade.js +98 -0
  15. package/dist/check.js +854 -0
  16. package/dist/cluster.js +69 -0
  17. package/dist/config.js +195 -0
  18. package/dist/content-mappers.js +83 -0
  19. package/dist/decision.js +203 -0
  20. package/dist/fingerprint.js +61 -0
  21. package/dist/git.js +127 -0
  22. package/dist/gitignore.js +65 -0
  23. package/dist/glob.js +51 -0
  24. package/dist/imports.js +153 -0
  25. package/dist/jsonc.js +95 -0
  26. package/dist/main.js +630 -0
  27. package/dist/manifest.js +42 -0
  28. package/dist/meta.js +170 -0
  29. package/dist/moves.js +47 -0
  30. package/dist/operation.js +133 -0
  31. package/dist/parsecache.js +264 -0
  32. package/dist/plans.js +425 -0
  33. package/dist/plugin.js +71 -0
  34. package/dist/plugins.js +136 -0
  35. package/dist/policy.js +676 -0
  36. package/dist/presets/composition.js +32 -0
  37. package/dist/report.js +474 -0
  38. package/dist/reporting.js +132 -0
  39. package/dist/result.js +28 -0
  40. package/dist/roles.js +303 -0
  41. package/dist/rule.js +194 -0
  42. package/dist/rules/append-only-honoured.js +190 -0
  43. package/dist/rules/bundle-conformance.js +245 -0
  44. package/dist/rules/call-pattern.js +209 -0
  45. package/dist/rules/cluster-verdict.js +700 -0
  46. package/dist/rules/compose-types.js +250 -0
  47. package/dist/rules/data-error-as-outage.js +482 -0
  48. package/dist/rules/declared-staleness.js +242 -0
  49. package/dist/rules/dependency-fit.js +297 -0
  50. package/dist/rules/deviation-has-a-shape.js +225 -0
  51. package/dist/rules/doc-matches-code.js +191 -0
  52. package/dist/rules/duplicate-call-run.js +240 -0
  53. package/dist/rules/duplicate-implementation.js +89 -0
  54. package/dist/rules/duplicate-meaning.js +130 -0
  55. package/dist/rules/fact-or-derivation.js +202 -0
  56. package/dist/rules/field-type-drift.js +373 -0
  57. package/dist/rules/generic-carries-a-caller.js +198 -0
  58. package/dist/rules/hoist-to-domain.js +288 -0
  59. package/dist/rules/import-architecture.js +393 -0
  60. package/dist/rules/index.js +105 -0
  61. package/dist/rules/inferred-over-recorded.js +214 -0
  62. package/dist/rules/intent-drift.js +286 -0
  63. package/dist/rules/invariant-has-a-reconciler.js +190 -0
  64. package/dist/rules/language-drift.js +234 -0
  65. package/dist/rules/meaning-switched-by-flag.js +189 -0
  66. package/dist/rules/module-direction.js +231 -0
  67. package/dist/rules/name-as-address.js +216 -0
  68. package/dist/rules/name-the-primitive.js +203 -0
  69. package/dist/rules/naming-drift.js +218 -0
  70. package/dist/rules/nullability-drift.js +220 -0
  71. package/dist/rules/object-shape.js +280 -0
  72. package/dist/rules/one-concept-one-type.js +243 -0
  73. package/dist/rules/page-needs-composition.js +227 -0
  74. package/dist/rules/reimplemented-primitive.js +283 -0
  75. package/dist/rules/reversal.js +264 -0
  76. package/dist/rules/rule-judgment.js +252 -0
  77. package/dist/rules/schema-excludes-domain-value.js +190 -0
  78. package/dist/rules/shallow-module.js +204 -0
  79. package/dist/rules/single-path.js +237 -0
  80. package/dist/rules/structural-collapse.js +198 -0
  81. package/dist/rules/temporal-coupling.js +205 -0
  82. package/dist/rules/types-over-logic.js +198 -0
  83. package/dist/rules/unaccounted-drop.js +190 -0
  84. package/dist/rules/unbounded-default-read.js +227 -0
  85. package/dist/run-cache.js +132 -0
  86. package/dist/schema.js +285 -0
  87. package/dist/similarity.js +119 -0
  88. package/dist/source.js +30 -0
  89. package/dist/sql.js +34 -0
  90. package/dist/stages.js +39 -0
  91. package/dist/state.js +65 -0
  92. package/dist/testing.js +131 -0
  93. package/dist/tsconfig-scope.js +32 -0
  94. package/dist/tsgo.js +127 -0
  95. package/dist/typefacts.js +455 -0
  96. package/dist/typetrace.js +283 -0
  97. package/dist/verdict.js +65 -0
  98. package/dist/vocabulary.js +365 -0
  99. package/dist/workspace.js +1963 -0
  100. package/extensions/joggle.ts +454 -0
  101. package/package.json +85 -3
@@ -0,0 +1,131 @@
1
+ import { Effect, Layer } from "effect";
2
+ import * as AiError from "effect/ai/AiError";
3
+ import { DecisionModel } from "effect/ai";
4
+ import { Atoms, layer as atomsLayer } from "./atoms.js";
5
+ import { unavailableFor } from "./config.js";
6
+ import { decisionError, isUnreachable } from "./decision.js";
7
+ import { answerPlans, PlanAnswers } from "./plans.js";
8
+ import { countUnjudged, everyFile } from "./rule.js";
9
+ /** The shared atom store, fresh per provide. */
10
+ export { atomsLayer };
11
+ /**
12
+ * An answer cache that never remembers.
13
+ *
14
+ * A test that is not about caching should not have one, and a test that is can
15
+ * provide a real store. What matters is that the engine always has a store to
16
+ * ask, so a rule under test never has to know which kind it got.
17
+ */
18
+ export const planAnswersLayer = Layer.succeed(PlanAnswers, {
19
+ get: () => Effect.succeedNone,
20
+ put: () => Effect.void,
21
+ });
22
+ /** A model layer, with the shared services every judged rule now needs. */
23
+ const withShared = (layer) => Layer.mergeAll(layer, atomsLayer, planAnswersLayer);
24
+ /** Run a rule against a workspace and return its findings, for a test. */
25
+ export const diagnosticsOf = (rule, workspace, options = {}) => rule.run(workspace, everyFile, options.context ?? { config: {} }).pipe(Effect.map((result) => result.diagnostics), Effect.provide(options.model ?? refusingModel("this rule asked for a judgement and none was provided")));
26
+ /**
27
+ * Run a planned rule the way the engine does, for one rule.
28
+ *
29
+ * The engine answers every planned rule's questions in one request; a test of one
30
+ * rule wants the same three moves -- plan, answer, read -- without the rest of the
31
+ * registry. The degrade behaviour matches the engine's, so a test can see what a
32
+ * rule does when the model is unreachable.
33
+ */
34
+ export const plannedDiagnosticsOf = (rule, workspace, context = { config: {} }) => Effect.gen(function* () {
35
+ const planned = yield* rule.plan(workspace, everyFile, context);
36
+ const unavailable = unavailableFor(context.config, rule.id, rule.onUnavailable);
37
+ let unreachable = false;
38
+ const answers = yield* answerPlans(planned.plans).pipe(Effect.catch((error) => {
39
+ if (unavailable === "propagate" && isUnreachable(error))
40
+ return Effect.fail(error);
41
+ unreachable = isUnreachable(error);
42
+ return Effect.succeed(planned.plans.map(() => undefined));
43
+ }));
44
+ const result = planned.read(answers);
45
+ return unreachable && unavailable === "count"
46
+ ? countUnjudged(result, "no judgement was available")
47
+ : result;
48
+ });
49
+ /** A model that answers every decision from one table. */
50
+ export const answeringModel = (answers) => decisionStub(answers);
51
+ /** A model that cannot answer, for testing what a rule does without one. */
52
+ export const refusingModel = (reason) => withShared(Layer.effect(DecisionModel.DecisionModel, DecisionModel.make({
53
+ decide: () => Effect.fail(decisionError(["@autotelic/joggle/testing", "decide"], AiError.UnknownError.make({ description: reason }))),
54
+ })));
55
+ /**
56
+ * The name a test wrote, from the name the engine sent.
57
+ *
58
+ * The engine disambiguates a decision with the plan that asked it
59
+ * (`verdict@3`), because two plans ask the same names. A test names the
60
+ * decision, so the suffix is stripped before the lookup.
61
+ */
62
+ // A request name back to the decision's own name. The engine disambiguates a
63
+ // decision by the plan that asked it (`name@3`), and a Noul asked `repeats` times
64
+ // adds the ask (`name@3~1`), so both suffixes come off.
65
+ const localName = (key) => key.replace(/~\d+$/, "").replace(/@\d+$/, "");
66
+ /**
67
+ * A DecisionModel that answers from a table of answers.
68
+ *
69
+ * The tests are about policy, so the model is a stub. A distribution with labels
70
+ * missing gets the remainder spread over them, so a test can name only the
71
+ * options it is about and still pass Effect's validation.
72
+ */
73
+ export const decisionStub = (supplied = {}) => withShared(Layer.effect(DecisionModel.DecisionModel, DecisionModel.make({
74
+ decide: ({ decisions }) => Effect.succeed({
75
+ answers: Object.fromEntries(Object.entries(decisions).map(([key, decision]) => {
76
+ const answer = supplied[localName(key)];
77
+ if (decision._tag === "Classify") {
78
+ const labels = Object.keys(decision.criteria);
79
+ const label = answer !== undefined && answer.type === "choice" ? answer.choice : (labels[0] ?? "");
80
+ const given = answer !== undefined && answer.type === "choice" ? answer.probabilities : {};
81
+ const missing = labels.filter((candidate) => given[candidate] === undefined);
82
+ const total = Object.values(given).reduce((sum, value) => sum + value, 0);
83
+ const remainder = missing.length === 0 ? 0 : Math.max(0, (1 - total) / missing.length);
84
+ return [
85
+ key,
86
+ {
87
+ _tag: "Classify",
88
+ label,
89
+ probabilities: Object.fromEntries(labels.map((candidate) => [candidate, given[candidate] ?? remainder])),
90
+ confidence: answer !== undefined && answer.type === "choice" ? answer.confidence : 0.9,
91
+ },
92
+ ];
93
+ }
94
+ if (decision._tag === "Rate") {
95
+ const levels = decision.criteria;
96
+ if (answer === undefined || answer.type !== "rate") {
97
+ return [
98
+ key,
99
+ {
100
+ _tag: "Rate",
101
+ rating: 0,
102
+ probabilities: Object.fromEntries(levels.map((level, index) => [level.label, index === 0 ? 1 : 0])),
103
+ confidence: 0.9,
104
+ },
105
+ ];
106
+ }
107
+ const provided = answer.probabilities ?? {};
108
+ const missing = levels.filter((level) => provided[level.label] === undefined);
109
+ const total = Object.values(provided).reduce((sum, value) => sum + value, 0);
110
+ const remainder = missing.length === 0 ? 0 : Math.max(0, (1 - total) / missing.length);
111
+ return [
112
+ key,
113
+ {
114
+ _tag: "Rate",
115
+ rating: answer.rating,
116
+ probabilities: Object.fromEntries(levels.map((level) => [level.label, provided[level.label] ?? remainder])),
117
+ confidence: answer.confidence ?? 0.9,
118
+ },
119
+ ];
120
+ }
121
+ return [
122
+ key,
123
+ {
124
+ _tag: "Probability",
125
+ probability: answer !== undefined && answer.type === "noul" ? answer.noul : 0.9,
126
+ },
127
+ ];
128
+ })),
129
+ usage: { inputTokens: 0, outputTokens: 0 },
130
+ }),
131
+ })));
@@ -0,0 +1,32 @@
1
+ import { Effect, FileSystem, Path, Result, Schema, SchemaParser } from "effect";
2
+ import { tsconfigEntry } from "./glob.js";
3
+ import { stripJsonc } from "./jsonc.js";
4
+ /*
5
+ * The root tsconfig's `include` and `exclude`, for files the compiler cannot list.
6
+ *
7
+ * tsgo applies them to every file it lists; an `.astro` file found by walking
8
+ * has to be held to the same scope, or a run reads what the project excluded.
9
+ * Only the root file is read: `extends` is not followed. JSONC is accepted, so a
10
+ * commented tsconfig is read rather than treated as "nothing declared".
11
+ */
12
+ const TsconfigScope = Schema.Struct({
13
+ include: Schema.optionalKey(Schema.Array(Schema.String)),
14
+ exclude: Schema.optionalKey(Schema.Array(Schema.String)),
15
+ });
16
+ const decodeTsconfig = SchemaParser.decodeUnknownResult(Schema.fromJsonString(TsconfigScope));
17
+ const everything = () => true;
18
+ /** Whether a root-relative, `/`-separated path is in the project the root tsconfig describes. */
19
+ export const tsconfigScope = (root) => Effect.gen(function* () {
20
+ const fs = yield* FileSystem.FileSystem;
21
+ const path = yield* Path.Path;
22
+ const body = yield* Effect.orElseSucceed(fs.readFileString(path.join(root, "tsconfig.json")), () => undefined);
23
+ if (body === undefined)
24
+ return everything;
25
+ const decoded = Result.getOrUndefined(decodeTsconfig(stripJsonc(body)));
26
+ if (decoded === undefined)
27
+ return everything;
28
+ const include = (decoded.include ?? []).map(tsconfigEntry);
29
+ const exclude = (decoded.exclude ?? []).map(tsconfigEntry);
30
+ return (file) => (include.length === 0 || include.some((matches) => matches(file))) &&
31
+ !exclude.some((matches) => matches(file));
32
+ });
package/dist/tsgo.js ADDED
@@ -0,0 +1,127 @@
1
+ import { Context, Effect, FileSystem, Layer, Order, Path, Stream } from "effect";
2
+ import { ChildProcess } from "effect/process";
3
+ import { resolve, sep } from "node:path";
4
+ import { TsgoError } from "./schema.js";
5
+ import { looksLikeSource } from "./source.js";
6
+ /**
7
+ * The tsgo process surface.
8
+ *
9
+ * `ChildProcessSpawner` is passed through on purpose: running the compiler IS
10
+ * this service's job, and the spawner is the tool it runs with. The requirement
11
+ * is the service's purpose, not a leak.
12
+ *
13
+ * @effect-expect-leaking ChildProcessSpawner
14
+ */
15
+ export class Service extends Context.Service()("@joggle/Tsgo") {
16
+ }
17
+ /* -------------------------------------------------------------------------- */
18
+ /* Implementation */
19
+ /* -------------------------------------------------------------------------- */
20
+ const DIAGNOSTIC = /^(.+?)\((\d+),(\d+)\): (error|warning) (TS\d+): (.*)$/;
21
+ const run = ({ binary, args, cwd, }) => Effect.scoped(Effect.gen(function* () {
22
+ const handle = yield* ChildProcess.make(binary, [...args], { cwd });
23
+ const [stdout, stderr] = yield* Effect.all([
24
+ handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
25
+ handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
26
+ ], { concurrency: "unbounded" });
27
+ return { stdout, stderr };
28
+ })).pipe(Effect.mapError((cause) => TsgoError.make({
29
+ operation: `tsc ${args.join(" ")}`,
30
+ detail: cause instanceof Error ? cause.message : String(cause),
31
+ })));
32
+ /**
33
+ * Whether the compiler's absolute path is inside the analysed root.
34
+ *
35
+ * Resolved on both sides: the root can be relative (it was, at the CLI
36
+ * boundary, before it was normalized), and `startsWith` on raw strings also
37
+ * accepts a sibling whose name merely begins with the root.
38
+ */
39
+ const underRoot = ({ cwd, file }) => {
40
+ const root = resolve(cwd);
41
+ const candidate = resolve(file);
42
+ return candidate === root || candidate.startsWith(root + sep);
43
+ };
44
+ const parseDiagnostics = (output) => {
45
+ const found = [];
46
+ for (const line of output.split(/\r?\n/)) {
47
+ const match = DIAGNOSTIC.exec(line);
48
+ if (match === null)
49
+ continue;
50
+ const file = match[1];
51
+ const lineNumber = match[2];
52
+ const column = match[3];
53
+ const severity = match[4];
54
+ const code = match[5];
55
+ const message = match[6];
56
+ if (file === undefined ||
57
+ lineNumber === undefined ||
58
+ column === undefined ||
59
+ severity === undefined ||
60
+ code === undefined ||
61
+ message === undefined) {
62
+ continue;
63
+ }
64
+ found.push({
65
+ file,
66
+ line: Number.parseInt(lineNumber, 10),
67
+ column: Number.parseInt(column, 10),
68
+ severity: severity === "error" ? "error" : "warning",
69
+ code,
70
+ message,
71
+ });
72
+ }
73
+ return found;
74
+ };
75
+ /**
76
+ * The compiler's arguments, with the content-mapper opt-in in front.
77
+ *
78
+ * `--runExternalCode` is not a performance switch: it lets `tsc` execute the
79
+ * mapper packages a tsconfig names. It is off unless the run asked for it, so a
80
+ * cloned repository cannot make an agent execute code by declaring a mapper.
81
+ */
82
+ export const compilerArgs = (args, runExternalCode) => (runExternalCode ? ["--runExternalCode", ...args] : args);
83
+ const make = (binary, path, runExternalCode) => {
84
+ const listFiles = Effect.fn("Tsgo.listFiles")(function* (cwd) {
85
+ const result = yield* run({ binary, args: compilerArgs(["--listFilesOnly"], runExternalCode), cwd });
86
+ const files = new Set();
87
+ for (const raw of result.stdout.split(/\r?\n/)) {
88
+ const file = raw.trim();
89
+ if (!looksLikeSource(file))
90
+ continue;
91
+ if (!underRoot({ cwd, file }))
92
+ continue;
93
+ files.add(path.resolve(file));
94
+ }
95
+ return [...files].sort(Order.String);
96
+ });
97
+ const typecheck = Effect.fn("Tsgo.typecheck")(function* (cwd) {
98
+ const result = yield* run({
99
+ binary,
100
+ args: compilerArgs(["--noEmit", "--pretty", "false"], runExternalCode),
101
+ cwd,
102
+ });
103
+ return parseDiagnostics(`${result.stdout}\n${result.stderr}`);
104
+ });
105
+ const generateTrace = Effect.fn("Tsgo.generateTrace")(function* (cwd, outDir) {
106
+ yield* run({
107
+ binary,
108
+ args: compilerArgs(["--generateTrace", outDir, "--noEmit"], runExternalCode),
109
+ cwd,
110
+ });
111
+ });
112
+ return Service.of({ listFiles, typecheck, generateTrace });
113
+ };
114
+ /**
115
+ * The tsgo binary is resolved by the caller because only the caller knows the
116
+ * project root. Everything else about the adapter is a plain subprocess
117
+ * boundary: build args, run, parse, map failures to a typed error.
118
+ */
119
+ export const layer = (binary, options = {}) => Layer.effect(Service, Effect.map(Path.Path, (path) => make(binary, path, options.runExternalCode ?? false)));
120
+ /** Resolve the project's own compiler, falling back to PATH. */
121
+ export const layerFromConfig = (root, options = {}) => Layer.effect(Service, Effect.gen(function* () {
122
+ const fs = yield* FileSystem.FileSystem;
123
+ const path = yield* Path.Path;
124
+ const local = path.join(root, "node_modules", ".bin", "tsc");
125
+ const resolved = (yield* Effect.orElseSucceed(fs.exists(local), () => false)) ? local : "tsc";
126
+ return make(resolved, path, options.runExternalCode ?? false);
127
+ }));