@uniqbit/mate-core 1.0.0-canary.6 → 1.0.0-canary.7

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 (168) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/cli/commands/doctor.ts +51 -0
  4. package/src/cli/commands/friction.ts +558 -0
  5. package/src/cli/commands/studio/connection.ts +53 -0
  6. package/src/cli/commands/studio/routes.ts +3 -0
  7. package/src/cli/commands/studio/selection.ts +10 -1
  8. package/src/cli/commands/studio/server.ts +31 -0
  9. package/src/cli/commands/studio/services.ts +25 -0
  10. package/src/cli/commands/triage.ts +151 -0
  11. package/src/cli/commands/vscode/release-vsix.json +2 -2
  12. package/src/cli/main.ts +35 -13
  13. package/src/cli/plugin-commands.ts +6 -1
  14. package/src/cli/usage.ts +10 -0
  15. package/src/create-mate.ts +11 -5
  16. package/src/distribution.ts +2 -0
  17. package/src/hooks/validate-artifact-path.ts +64 -14
  18. package/src/lib/friction/describe.ts +42 -0
  19. package/src/lib/friction/fields.ts +60 -0
  20. package/src/lib/friction/mark.ts +156 -0
  21. package/src/lib/friction/view/model.ts +67 -0
  22. package/src/lib/friction/view/read.ts +136 -0
  23. package/src/lib/friction/view/select.ts +54 -0
  24. package/src/lib/orchestrator/adapters/claude.ts +5 -4
  25. package/src/lib/orchestrator/adapters/opencode.ts +2 -0
  26. package/src/lib/orchestrator/root-context.ts +23 -6
  27. package/src/lib/package-paths.ts +23 -15
  28. package/src/lib/session-attribution.ts +3 -7
  29. package/src/lib/triage/context.ts +186 -0
  30. package/src/lib/triage/launch.ts +52 -0
  31. package/src/lib/triage/prepare.ts +97 -0
  32. package/src/lib/triage/session.ts +126 -0
  33. package/src/opencode/companion-hooks.ts +53 -5
  34. package/src/opencode/projected-guidance.ts +2 -0
  35. package/src/playbooks/companion-guidance.ts +2 -2
  36. package/src/plugin-api.ts +5 -0
  37. package/src/runtime/command-friction.ts +97 -0
  38. package/src/runtime/companion-guidance.ts +32 -15
  39. package/src/runtime/friction-fingerprint.ts +35 -0
  40. package/src/runtime/friction-log.ts +352 -0
  41. package/src/runtime/friction-recorder.ts +199 -0
  42. package/src/runtime/friction-retention.ts +1 -0
  43. package/src/runtime/friction-state.ts +110 -0
  44. package/src/runtime/friction-switch.ts +26 -0
  45. package/src/runtime/friction-vocabulary.ts +42 -0
  46. package/src/runtime/projected-guidance.ts +2 -1
  47. package/src/runtime/secret-values.ts +16 -0
  48. package/src/runtime/session-id.ts +24 -0
  49. package/src/runtime/session-prepare-runner.ts +3 -0
  50. package/src/runtime/workflow/next-handoff-process.ts +2 -1
  51. package/src/studio.ts +41 -0
  52. package/src/templates/triage/PLAYBOOK.md +112 -0
  53. package/src/tools/setup/capabilities/rtk.ts +19 -8
  54. package/src/tools/setup/plugin.ts +5 -0
  55. package/src/tools/setup/service.ts +4 -0
  56. package/src/tools/setup.ts +16 -2
  57. package/studio-dist/client/assets/app-aIwDxf48.css +2 -0
  58. package/studio-dist/client/assets/button-CX0sWAJl.js +1 -0
  59. package/studio-dist/client/assets/combobox-BmA8RjOc.js +1 -0
  60. package/studio-dist/client/assets/{companion-view-BVaZNtiI.js → companion-view-DINdPF-b.js} +1 -1
  61. package/studio-dist/client/assets/fields-BobQ7zRF.js +1 -0
  62. package/studio-dist/client/assets/friction-YdYd3zaz.js +1 -0
  63. package/studio-dist/client/assets/getting-started-CY7NEtTw.js +1 -0
  64. package/studio-dist/client/assets/getting-started-djaQeWlu.js +1 -0
  65. package/studio-dist/client/assets/getting-started._topic-DVB8e5R9.js +1 -0
  66. package/studio-dist/client/assets/getting-started.index-DQvLHEr1.js +1 -0
  67. package/studio-dist/client/assets/graph-DbNnR884.js +2 -0
  68. package/studio-dist/client/assets/{graph-canvas-DDuzsNSx.js → graph-canvas-DIcAqwtK.js} +1 -1
  69. package/studio-dist/client/assets/guides-D6T6W_jV.js +1 -0
  70. package/studio-dist/client/assets/index-CysBCSxM.js +40 -0
  71. package/studio-dist/client/assets/markdown-view-jMiaBTSO.js +1 -0
  72. package/studio-dist/client/assets/{panel-B8F8sOKQ.js → panel-Csr49lBo.js} +1 -1
  73. package/studio-dist/client/assets/plugins._service._view-CEA_CcPe.js +1 -0
  74. package/studio-dist/client/assets/prepaint-CKsXyJOR.js +27 -0
  75. package/studio-dist/client/assets/{queries-axYk2u9L.js → queries-Dfp5deWj.js} +1 -1
  76. package/studio-dist/client/assets/react-BYUSgtBs.js +1 -0
  77. package/studio-dist/client/assets/reports-CLdgxxkg.js +1 -0
  78. package/studio-dist/client/assets/routes-DGilWbDE.js +1 -0
  79. package/studio-dist/client/assets/search-CXosfvYh.js +1 -0
  80. package/studio-dist/client/assets/select-DdebbX7K.js +1 -0
  81. package/studio-dist/client/assets/skills-C3zNkU8g.js +1 -0
  82. package/studio-dist/client/assets/{specs-DU1kqcp5.js → specs-Dl8HfGlU.js} +1 -1
  83. package/studio-dist/client/assets/specs-view-B_n0Pekv.js +1 -0
  84. package/studio-dist/client/assets/{steps-DhIFuAZy.js → steps-CKUno4lh.js} +1 -1
  85. package/studio-dist/client/assets/store-DyXbi6o9.js +1 -0
  86. package/studio-dist/client/assets/{studio-BR9j15J0.js → studio-0ueISxwP.js} +8 -8
  87. package/studio-dist/client/assets/{studio-queries-CFP_yTpr.js → studio-queries-BflKt9va.js} +2 -2
  88. package/studio-dist/client/assets/{usage-CHmwtkoM.js → usage-Blcl8kA_.js} +16 -16
  89. package/studio-dist/client/assets/useAnchoredPopupScrollLock-BBXJpX5L.js +1 -0
  90. package/studio-dist/client/assets/{useBaseQuery-BlC-AZ35.js → useBaseQuery-C2cjmeH2.js} +1 -1
  91. package/studio-dist/client/assets/useMutation-DI6LbvVa.js +1 -0
  92. package/studio-dist/client/assets/vault-Cb9DmM1i.js +1 -0
  93. package/studio-dist/client/assets/warnings-B-rvoW8q.js +1 -0
  94. package/studio-dist/client/assets/workflow-DN5T19jd.js +1 -0
  95. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-DAbZ6fzY.js → __23tanstack-start-server-fn-resolver-JoHQ5ihx.js} +30 -14
  96. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +66 -50
  97. package/studio-dist/server/assets/{button-BfoNadNR.js → button-B7e1fRyW.js} +228 -3
  98. package/studio-dist/server/assets/combobox--S_OmUfh.js +483 -0
  99. package/studio-dist/server/assets/{companion-view-DHUjPpA0.js → companion-view-D-vGM55e.js} +2 -2
  100. package/studio-dist/server/assets/{companions-kBrJZAd6.js → companions-Dr6IpNAb.js} +1 -1
  101. package/studio-dist/server/assets/{fields-BD_c65T1.js → fields-B4qM2ZwC.js} +1 -1
  102. package/studio-dist/server/assets/friction-CWOTjpCV.js +62 -0
  103. package/studio-dist/server/assets/friction-sLxaWY-H.js +903 -0
  104. package/studio-dist/server/assets/{getting-started-7P0oyWaM.js → getting-started-Cq5Pcnsr.js} +2 -2
  105. package/studio-dist/server/assets/{getting-started._topic-B1mV0kGz.js → getting-started._topic-CmWdl3u3.js} +2 -2
  106. package/studio-dist/server/assets/{getting-started.index-CeGtvUsm.js → getting-started.index-AB8xpTFY.js} +2 -2
  107. package/studio-dist/server/assets/{graph-BWtmJOH2.js → graph-B11ITte0.js} +1 -1
  108. package/studio-dist/server/assets/{graph-DSDVEELZ.js → graph-C_Hn-Wf_.js} +7 -8
  109. package/studio-dist/server/assets/{graph-canvas-CID9Nksc.js → graph-canvas-BthrSmPS.js} +2 -2
  110. package/studio-dist/server/assets/{guides-Bm3RbUB-.js → guides-B8HdeK_C.js} +1 -1
  111. package/studio-dist/server/assets/{guides-BLJenHwQ.js → guides-BVQ4pt5B.js} +1 -1
  112. package/studio-dist/server/assets/{guides.server-rHHqRuzV.js → guides.server-DqFQAStf.js} +1 -1
  113. package/studio-dist/server/assets/{markdown-view-D3v9x-cM.js → markdown-view-rwiiVcPC.js} +1 -1
  114. package/studio-dist/server/assets/{panel-yqOl5GMU.js → panel-CUxRIpYL.js} +3 -3
  115. package/studio-dist/server/assets/{plugins._service._view-DwqJX7s9.js → plugins._service._view-BSvGnlhU.js} +6 -4
  116. package/studio-dist/server/assets/prepaint-B28ClcPN.js +45 -0
  117. package/studio-dist/server/assets/{queries-DYmGrhNO.js → queries-S_Pl90IG.js} +1 -1
  118. package/studio-dist/server/assets/react-CiBZPDs8.js +45 -0
  119. package/studio-dist/server/assets/{reports-C4Y_Jd-x.js → reports-B9k98oE6.js} +1 -1
  120. package/studio-dist/server/assets/{reports-7yaPz7aP.js → reports-CJpAItPk.js} +6 -7
  121. package/studio-dist/server/assets/{router-Dnoq5auE.js → router-DF0etoNa.js} +627 -1563
  122. package/studio-dist/server/assets/{routes-Cok4p3mK.js → routes-6ylCLkyg.js} +7 -8
  123. package/studio-dist/server/assets/{search-DUK7Jl6f.js → search-b-yQesv3.js} +25 -2
  124. package/studio-dist/server/assets/{combobox-oxUI6r4V.js → select-CjuKScan.js} +34 -514
  125. package/studio-dist/server/assets/{shell-DNVXedgE.js → shell-DLkP7wG9.js} +2 -2
  126. package/studio-dist/server/assets/{skills-pKmuAs0F.js → skills-DGg0mWDM.js} +1 -1
  127. package/studio-dist/server/assets/{skills-D8qdXSku.js → skills-zeU80A9S.js} +7 -8
  128. package/studio-dist/server/assets/{specs-DeHYUNFp.js → specs-DDBNT_v1.js} +4 -4
  129. package/studio-dist/server/assets/{specs-view-BGn-5Ik_.js → specs-view-exvmWdg0.js} +9 -9
  130. package/studio-dist/server/assets/{steps-CV7Yk7L7.js → steps-D1tYAyWZ.js} +1 -1
  131. package/studio-dist/server/assets/store-kS7zk0Hr.js +93 -0
  132. package/studio-dist/server/assets/{studio-CB94np48.js → studio-qRvQjRpz.js} +47 -2
  133. package/studio-dist/server/assets/{studio-queries-BqZGBE70.js → studio-queries-qOXOYoPt.js} +66 -8
  134. package/studio-dist/server/assets/{usage-M6Gi6Km7.js → usage-C2um7YiV.js} +12 -43
  135. package/studio-dist/server/assets/{usage-j5jR9gX9.js → usage-Cwle9-xY.js} +1 -1
  136. package/studio-dist/server/assets/useAnchoredPopupScrollLock-kQBB3y_b.js +756 -0
  137. package/studio-dist/server/assets/{useBaseQuery-Tv_QJt9r.js → useBaseQuery--iH3rd-T.js} +1 -1
  138. package/studio-dist/server/assets/useMutation-C-WO6hCM.js +690 -0
  139. package/studio-dist/server/assets/{vault-PqVmssmW.js → vault-B8vgVIH9.js} +6 -6
  140. package/studio-dist/server/assets/{vault-lBlvSyD4.js → vault-CEBBRLMb.js} +1 -1
  141. package/studio-dist/server/assets/{views-CsFp1i1G.js → views-UgO0Qz_g.js} +2 -2
  142. package/studio-dist/server/assets/{warnings-BDs34j_m.js → warnings-BxK4VfV5.js} +1 -2
  143. package/studio-dist/server/assets/{workflow-T0eEldsa.js → workflow-BrTK632u.js} +8 -9
  144. package/studio-dist/server/server.js +2 -2
  145. package/studio-dist/client/assets/app-BFVyWHGo.css +0 -2
  146. package/studio-dist/client/assets/button-D6LrRkOG.js +0 -1
  147. package/studio-dist/client/assets/combobox-Dk2MMZWE.js +0 -1
  148. package/studio-dist/client/assets/fields-D_FYhxQr.js +0 -1
  149. package/studio-dist/client/assets/getting-started-ByWRg7hC.js +0 -1
  150. package/studio-dist/client/assets/getting-started-DZSjYC-b.js +0 -1
  151. package/studio-dist/client/assets/getting-started._topic-C6OyQ4G6.js +0 -1
  152. package/studio-dist/client/assets/getting-started.index-BkmPHdEm.js +0 -1
  153. package/studio-dist/client/assets/graph-7jm2XzyL.js +0 -2
  154. package/studio-dist/client/assets/guides-D9VTjWXP.js +0 -1
  155. package/studio-dist/client/assets/index-BBmFpG4y.js +0 -40
  156. package/studio-dist/client/assets/markdown-view-RL5YvfZg.js +0 -1
  157. package/studio-dist/client/assets/plugins._service._view-CynxTbMx.js +0 -1
  158. package/studio-dist/client/assets/react-r45OnJCw.js +0 -27
  159. package/studio-dist/client/assets/reports-BCAyXh6p.js +0 -1
  160. package/studio-dist/client/assets/routes-BFPqq89E.js +0 -1
  161. package/studio-dist/client/assets/skills-DTks_uBx.js +0 -1
  162. package/studio-dist/client/assets/specs-view-omrd_5P3.js +0 -1
  163. package/studio-dist/client/assets/store-DJ5cncKA.js +0 -1
  164. package/studio-dist/client/assets/vault-DRg8MScm.js +0 -1
  165. package/studio-dist/client/assets/warnings-UHFy6HAp.js +0 -1
  166. package/studio-dist/client/assets/workflow-Bv9vSfVV.js +0 -1
  167. package/studio-dist/server/assets/react-BO0uMhpm.js +0 -89
  168. package/studio-dist/server/assets/store-CWDGIp6x.js +0 -280
package/src/plugin-api.ts CHANGED
@@ -15,6 +15,11 @@ export type {
15
15
  SetupContext,
16
16
  SetupScope,
17
17
  } from "./tools/setup/plugin";
18
+ export type {
19
+ StudioConnection,
20
+ StudioConnectionProblem,
21
+ StudioConnectionState,
22
+ } from "./cli/commands/studio/connection";
18
23
  export type { ClaudeHookCommand, ClaudeHookGroup } from "./runtime/claude-hook-group";
19
24
  export type {
20
25
  CompanionSourceResult,
@@ -0,0 +1,97 @@
1
+ import { format } from "node:util";
2
+
3
+ import type { FrictionRuntime } from "./friction-log";
4
+ import { recordCommandFailure, redactCommandOutput } from "./friction-recorder";
5
+
6
+ interface CommandRun {
7
+ /** Arguments after the executable and script. */
8
+ args: string[];
9
+ /** The agent session the command runs in; without one nothing is captured or recorded. */
10
+ session: { id: string; runtime: FrictionRuntime } | null;
11
+ mateVersion: string;
12
+ }
13
+
14
+ /**
15
+ * Runs a command and prints what it throws. In an agent session a non-zero exit
16
+ * is recorded as friction with the tail of its stderr, and any nudge follows the
17
+ * command's own output. The exit code is the command's.
18
+ */
19
+ export async function runRecordingFailure(
20
+ { args, session, mateVersion }: CommandRun,
21
+ run: () => Promise<void>,
22
+ ): Promise<void> {
23
+ const errors = session
24
+ ? captureErrorTail((text) => redactCommandOutput(text, args, process.env))
25
+ : null;
26
+ const record = (exitCode: number) => {
27
+ if (!session || !errors || exitCode === 0) return;
28
+ try {
29
+ const nudge = recordCommandFailure({
30
+ args,
31
+ exitCode,
32
+ errorText: errors.text(),
33
+ session,
34
+ mateVersion,
35
+ env: process.env,
36
+ cwd: process.cwd(),
37
+ });
38
+ if (nudge) process.stderr.write(`${nudge}\n`);
39
+ } catch {}
40
+ };
41
+ if (session) process.once("exit", record);
42
+ try {
43
+ await run();
44
+ } catch (error) {
45
+ console.error(error instanceof Error ? error.message : String(error));
46
+ process.exitCode = 1;
47
+ } finally {
48
+ process.off("exit", record);
49
+ errors?.restore();
50
+ }
51
+ record(Number(process.exitCode ?? 0));
52
+ }
53
+
54
+ const ERROR_TAIL_LIMIT = 1_000;
55
+
56
+ function captureErrorTail(redact: (text: string) => string): {
57
+ text(): string;
58
+ restore(): void;
59
+ } {
60
+ const originalError = console.error;
61
+ const originalWrite = process.stderr.write;
62
+ let tail = "";
63
+ // Node's console.error writes through process.stderr.write; Bun's does not.
64
+ let inConsoleError = false;
65
+ const append = (piece: () => string) => {
66
+ try {
67
+ tail = `${tail}${redact(piece())}`.slice(-ERROR_TAIL_LIMIT);
68
+ } catch {}
69
+ };
70
+ const error = (...args: unknown[]) => {
71
+ inConsoleError = true;
72
+ try {
73
+ originalError(...args);
74
+ } finally {
75
+ inConsoleError = false;
76
+ }
77
+ append(() => `${format(...args)}\n`);
78
+ };
79
+ const write = ((chunk: unknown, ...rest: unknown[]) => {
80
+ const written = Reflect.apply(originalWrite, process.stderr, [chunk, ...rest]) as boolean;
81
+ if (!inConsoleError) {
82
+ append(() =>
83
+ typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString(),
84
+ );
85
+ }
86
+ return written;
87
+ }) as typeof process.stderr.write;
88
+ console.error = error;
89
+ process.stderr.write = write;
90
+ return {
91
+ text: () => tail,
92
+ restore: () => {
93
+ if (console.error === error) console.error = originalError;
94
+ if (process.stderr.write === write) process.stderr.write = originalWrite;
95
+ },
96
+ };
97
+ }
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
 
3
3
  import { FRAMEWORK_NAME } from "./framework";
4
+ import { REPORT_KINDS } from "./friction-vocabulary";
4
5
  import { GUIDANCE_FILE_VERSION, type MateGuidanceFile } from "./guidance";
5
6
  import { readWorkflow } from "./workflow/declaration";
6
7
  import type { DeclaredArtifactType } from "./workflow/workflow";
@@ -112,6 +113,14 @@ function artifactTypeRule(type: GuidanceArtifactType): string {
112
113
 
113
114
  const SECRET_HANDLING_RULE = ` <rule id="secret-handling" severity="critical">Never read, print, copy, or write secret files (.env, .env.*, keys, certificates, credential files such as .npmrc or .netrc) or secret values. To learn which variables exist, read only the example files (.env.example, .env.sample, .env.template, .env.dist). Refer to a secret by its variable name only. Do not print environment variables that may hold secrets. When a secret must be set or rotated, ask the user to do it instead of writing it yourself. Guarded calls are blocked; the companion's framework.yaml secrets block is the user's switch, not yours.</rule>`;
114
115
 
116
+ export const FRICTION_GUIDANCE = `## Friction
117
+
118
+ When ${FRAMEWORK_NAME} gets in your way without a refusal or error to point at, such as a skill step that does not fit or missing guidance, record it when it happens: \`${FRAMEWORK_NAME} friction report --kind <${REPORT_KINDS.join("|")}> --subject <type>:<name> --expected "<what you expected>" --evidence "<what you saw>"\`. Record one report per problem, then keep working on your task. When nothing went wrong, record nothing.`;
119
+
120
+ function withFriction(policy: string, friction: boolean | undefined): string {
121
+ return friction ? `${policy}\n\n${FRICTION_GUIDANCE}` : policy;
122
+ }
123
+
115
124
  export function hasGraphifyCapability(capabilities: GuidanceCapability[] = []): boolean {
116
125
  return capabilities.some((capability) => capability.name === "graphify");
117
126
  }
@@ -284,17 +293,21 @@ export function buildCompanionPolicyXml(
284
293
  }
285
294
 
286
295
  /**
287
- * Build the merged single-string guidance: the companion-policy XML plus
288
- * codebase-exploration guidance appended when graphify or tokensave is
289
- * enabled. Used by providers (e.g. Claude) that inject one combined prompt
296
+ * Build the merged single-string guidance: the companion-policy XML, the
297
+ * friction section while the Friction Switch is on, and codebase-exploration
298
+ * guidance appended when graphify or tokensave is enabled. Used by providers (e.g. Claude) that inject one combined prompt
290
299
  * fragment rather than delivering exploration guidance separately; only that
291
300
  * form carries the Claude-only `entered-worktree-git` rule.
292
301
  */
293
302
  export function buildCompanionGuidance(
294
303
  context: GuidanceContext,
295
- options: { wrapperBinPath: string },
304
+ options: { wrapperBinPath: string; friction?: boolean },
296
305
  ): string {
297
- const lines = [buildCompanionPolicyXml(context, { ...options, enteredWorktreeGit: true })];
306
+ const policy = buildCompanionPolicyXml(context, {
307
+ wrapperBinPath: options.wrapperBinPath,
308
+ enteredWorktreeGit: true,
309
+ });
310
+ const lines = [withFriction(policy, options.friction)];
298
311
 
299
312
  const graphifyEnabled = hasGraphifyCapability(context.capabilities);
300
313
  const tokensaveEnabled = hasTokensaveCapability(context.capabilities);
@@ -331,6 +344,7 @@ export function buildOpenCodeGuidance(
331
344
  options: {
332
345
  companionScoped?: boolean;
333
346
  secretGuardrails?: boolean;
347
+ friction?: boolean;
334
348
  artifactTypes?: readonly GuidanceArtifactType[];
335
349
  stages?: readonly GuidanceStage[];
336
350
  } = {},
@@ -338,16 +352,19 @@ export function buildOpenCodeGuidance(
338
352
  const repository = options.companionScoped
339
353
  ? undefined
340
354
  : { id: "$MATE_REPO_ID", path: "$MATE_REPO_PATH" };
341
- const companionGuidance = buildCompanionPolicyXml(
342
- {
343
- companionPath: "$MATE_ARTIFACT_PATH",
344
- repository,
345
- capabilities,
346
- secretGuardrails: options.secretGuardrails,
347
- ...(options.artifactTypes ? { artifactTypes: options.artifactTypes } : {}),
348
- ...(options.stages ? { stages: options.stages } : {}),
349
- },
350
- { wrapperBinPath: "$MATE_WRAPPER_BIN_PATH" },
355
+ const companionGuidance = withFriction(
356
+ buildCompanionPolicyXml(
357
+ {
358
+ companionPath: "$MATE_ARTIFACT_PATH",
359
+ repository,
360
+ capabilities,
361
+ secretGuardrails: options.secretGuardrails,
362
+ ...(options.artifactTypes ? { artifactTypes: options.artifactTypes } : {}),
363
+ ...(options.stages ? { stages: options.stages } : {}),
364
+ },
365
+ { wrapperBinPath: "$MATE_WRAPPER_BIN_PATH" },
366
+ ),
367
+ options.friction,
351
368
  );
352
369
  const graphifyEnabled = hasGraphifyCapability(capabilities);
353
370
  const tokensaveEnabled = hasTokensaveCapability(capabilities);
@@ -0,0 +1,35 @@
1
+ import type { SecretToolCall } from "./secret-guard";
2
+
3
+ export type FrictionCheck = "secret" | "attribution" | "artifact" | "fork";
4
+ /** The adapters' secret-guard classification; "other" for a tool it does not classify. */
5
+ export type ToolKind = SecretToolCall["kind"] | "other";
6
+
7
+ export function refusalFingerprint(check: FrictionCheck, kind: ToolKind): string {
8
+ return `refusal:${check}:${kind}`;
9
+ }
10
+
11
+ export function commandFingerprint(failure: {
12
+ command: string | null;
13
+ subcommand: string | null;
14
+ exitCode: number;
15
+ }): string {
16
+ const name = [failure.command ?? "", failure.subcommand]
17
+ .filter((part) => part !== null)
18
+ .join(" ");
19
+ return `command:${name}:${failure.exitCode}`;
20
+ }
21
+
22
+ export interface FingerprintParts {
23
+ /** `refusal` or `command` for a fingerprint Mate built. */
24
+ form: string;
25
+ /** The check of a refusal or the command words of a failed command; absent without a colon. */
26
+ name: string | undefined;
27
+ /** What follows the name: the tool kind of a refusal, the exit code of a failed command. */
28
+ rest: string[];
29
+ }
30
+
31
+ /** Splits any text; the caller decides whether the parts make a known fingerprint. */
32
+ export function parseFingerprint(fingerprint: string): FingerprintParts {
33
+ const [form, name, ...rest] = fingerprint.split(":");
34
+ return { form, name, rest };
35
+ }
@@ -0,0 +1,352 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { FRICTION_RETENTION_DAYS } from "./friction-retention";
6
+ import type { ReportCost, ReportKind } from "./friction-vocabulary";
7
+ import { realPath } from "./git-layout";
8
+ import { mateHome } from "./runtime-directory";
9
+ import type { SessionRuntime } from "./session-registry";
10
+
11
+ type FrictionKind = "refusal" | "command-failure";
12
+ export type FrictionRuntime = SessionRuntime;
13
+
14
+ export interface FrictionEvent {
15
+ v: 1;
16
+ id: string;
17
+ /** ISO 8601 UTC. */
18
+ at: string;
19
+ kind: FrictionKind;
20
+ fingerprint: string;
21
+ mateVersion: string;
22
+ runtime: FrictionRuntime;
23
+ sessionId: string;
24
+ companion: string;
25
+ repositoryPath: string | null;
26
+ detail: Record<string, unknown>;
27
+ }
28
+
29
+ export type NewFrictionEvent = Omit<FrictionEvent, "v" | "id" | "at">;
30
+
31
+ /** An agent's judgement on a Friction Event, or a free report on friction that has none. */
32
+ export interface FrictionReport {
33
+ v: 1;
34
+ id: string;
35
+ /** ISO 8601 UTC. */
36
+ at: string;
37
+ eventId: string | null;
38
+ kind: ReportKind;
39
+ cost: ReportCost | null;
40
+ subject: string;
41
+ expected: string;
42
+ evidence: string | null;
43
+ workaround: string | null;
44
+ mateVersion: string;
45
+ companion: string;
46
+ sessionId: string | null;
47
+ runtime: FrictionRuntime | null;
48
+ }
49
+
50
+ export type NewFrictionReport = Omit<FrictionReport, "v" | "id" | "at">;
51
+
52
+ type Family = "events" | "reports";
53
+
54
+ const DAY_MS = 24 * 60 * 60 * 1000;
55
+
56
+ function familyPattern(family: Family): RegExp {
57
+ return new RegExp(`^${family}-(\\d{4}-\\d{2})\\.jsonl$`);
58
+ }
59
+
60
+ export function frictionLogDir(homeDir?: string): string {
61
+ return path.join(mateHome(homeDir), "friction");
62
+ }
63
+
64
+ function monthOf(date: Date): string {
65
+ return date.toISOString().slice(0, 7);
66
+ }
67
+
68
+ function familyFile(family: Family, month: string, homeDir?: string): string {
69
+ return path.join(frictionLogDir(homeDir), `${family}-${month}.jsonl`);
70
+ }
71
+
72
+ export function frictionLogFile(month: string, homeDir?: string): string {
73
+ return familyFile("events", month, homeDir);
74
+ }
75
+
76
+ export function frictionReportFile(month: string, homeDir?: string): string {
77
+ return familyFile("reports", month, homeDir);
78
+ }
79
+
80
+ function logMonths(dir: string, family: Family): string[] {
81
+ const pattern = familyPattern(family);
82
+ return fs
83
+ .readdirSync(dir)
84
+ .map((name) => pattern.exec(name)?.[1])
85
+ .filter((month): month is string => Boolean(month));
86
+ }
87
+
88
+ function pruneExpiredMonths(family: Family, now: Date, homeDir?: string): void {
89
+ const oldestKept = monthOf(new Date(now.getTime() - FRICTION_RETENTION_DAYS * DAY_MS));
90
+ try {
91
+ for (const month of logMonths(frictionLogDir(homeDir), family)) {
92
+ if (month < oldestKept) fs.rmSync(familyFile(family, month, homeDir), { force: true });
93
+ }
94
+ } catch {}
95
+ }
96
+
97
+ interface AppendOptions {
98
+ homeDir?: string;
99
+ now?: Date;
100
+ }
101
+
102
+ function appendRecord<T extends object>(
103
+ family: Family,
104
+ fields: T,
105
+ options: AppendOptions,
106
+ ): T & { v: 1; id: string; at: string } {
107
+ const now = options.now ?? new Date();
108
+ const month = monthOf(now);
109
+ const dir = frictionLogDir(options.homeDir);
110
+ const file = familyFile(family, month, options.homeDir);
111
+ const record = { v: 1 as const, id: crypto.randomUUID(), at: now.toISOString(), ...fields };
112
+ fs.mkdirSync(dir, { recursive: true });
113
+ const startsMonth = !fs.existsSync(file);
114
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`, "utf8");
115
+ if (startsMonth) pruneExpiredMonths(family, now, options.homeDir);
116
+ return record;
117
+ }
118
+
119
+ /** Best effort: every failure is swallowed and returns null. */
120
+ export function appendEvent(
121
+ event: NewFrictionEvent,
122
+ options: AppendOptions = {},
123
+ ): FrictionEvent | null {
124
+ try {
125
+ return appendRecord("events", event, options);
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /** Unlike an event, a report is asked for, so a failed write throws. */
132
+ export function appendReport(
133
+ report: NewFrictionReport,
134
+ options: AppendOptions = {},
135
+ ): FrictionReport {
136
+ return appendRecord("reports", report, options);
137
+ }
138
+
139
+ function recordOf<T>(fields: string[]): (value: unknown) => value is T {
140
+ return (value): value is T => {
141
+ if (!value || typeof value !== "object") return false;
142
+ const record = value as Record<string, unknown>;
143
+ return record.v === 1 && fields.every((field) => typeof record[field] === "string");
144
+ };
145
+ }
146
+
147
+ const hasEventStrings = recordOf<FrictionEvent>([
148
+ "id",
149
+ "at",
150
+ "fingerprint",
151
+ "sessionId",
152
+ "companion",
153
+ ]);
154
+
155
+ function isFrictionEvent(value: unknown): value is FrictionEvent {
156
+ return hasEventStrings(value) && typeof value.detail === "object" && value.detail !== null;
157
+ }
158
+
159
+ const isFrictionReport = recordOf<FrictionReport>([
160
+ "id",
161
+ "at",
162
+ "kind",
163
+ "subject",
164
+ "expected",
165
+ "companion",
166
+ ]);
167
+
168
+ function parseLine<T>(line: string, accept: (value: unknown) => value is T): T | null {
169
+ try {
170
+ const parsed: unknown = JSON.parse(line);
171
+ return accept(parsed) ? parsed : null;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ interface ReadOptions {
178
+ sinceDays: number;
179
+ homeDir?: string;
180
+ now?: Date;
181
+ }
182
+
183
+ export type FrictionScope = { companion: string } | "all";
184
+
185
+ function companionFilter(target: string): (candidate: string) => boolean {
186
+ if (!target) return () => false;
187
+ const wanted = realPath(target);
188
+ const seen = new Map<string, boolean>();
189
+ return (candidate) => {
190
+ if (!candidate) return false;
191
+ let same = seen.get(candidate);
192
+ if (same === undefined) {
193
+ same = realPath(candidate) === wanted;
194
+ seen.set(candidate, same);
195
+ }
196
+ return same;
197
+ };
198
+ }
199
+
200
+ const isMissing = (error: unknown) => (error as NodeJS.ErrnoException)?.code === "ENOENT";
201
+
202
+ function scanMonth<T>(
203
+ family: Family,
204
+ month: string,
205
+ accept: (value: unknown) => value is T,
206
+ homeDir?: string,
207
+ ): { records: T[]; complete: boolean } {
208
+ let text: string;
209
+ try {
210
+ text = fs.readFileSync(familyFile(family, month, homeDir), "utf8");
211
+ } catch (error) {
212
+ return { records: [], complete: isMissing(error) };
213
+ }
214
+ const lines = text.split("\n").filter((line) => line.trim());
215
+ const records = lines
216
+ .map((line) => parseLine(line, accept))
217
+ .filter((record): record is T => record !== null);
218
+ return { records, complete: records.length === lines.length };
219
+ }
220
+
221
+ function readMonth<T>(
222
+ family: Family,
223
+ month: string,
224
+ accept: (value: unknown) => value is T,
225
+ homeDir?: string,
226
+ ): T[] {
227
+ return scanMonth(family, month, accept, homeDir).records;
228
+ }
229
+
230
+ function readFamily<T extends { at: string }>(
231
+ family: Family,
232
+ accept: (value: unknown) => value is T,
233
+ options: ReadOptions,
234
+ ): T[] {
235
+ const now = options.now ?? new Date();
236
+ const since = new Date(now.getTime() - options.sinceDays * DAY_MS);
237
+ const dir = frictionLogDir(options.homeDir);
238
+ let months: string[];
239
+ try {
240
+ months = logMonths(dir, family).filter((month) => month >= monthOf(since));
241
+ } catch {
242
+ return [];
243
+ }
244
+ return months
245
+ .toSorted()
246
+ .flatMap((month) => readMonth(family, month, accept, options.homeDir))
247
+ .filter((record) => {
248
+ const at = Date.parse(record.at);
249
+ return !Number.isNaN(at) && at >= since.getTime();
250
+ });
251
+ }
252
+
253
+ /** Every companion's events in the window, oldest file first. */
254
+ export function readEvents(options: ReadOptions): FrictionEvent[] {
255
+ return readFamily("events", isFrictionEvent, options);
256
+ }
257
+
258
+ /** Every companion's reports in the window, oldest file first. */
259
+ export function readReports(options: ReadOptions): FrictionReport[] {
260
+ return readFamily("reports", isFrictionReport, options);
261
+ }
262
+
263
+ /**
264
+ * A scope's events in the window, the reports on those events wherever they were made,
265
+ * and the scope's free reports.
266
+ */
267
+ export function readFriction(
268
+ scope: FrictionScope,
269
+ options: ReadOptions,
270
+ ): { events: FrictionEvent[]; reports: FrictionReport[] } {
271
+ const inScope = scope === "all" ? () => true : companionFilter(scope.companion);
272
+ const events = readEvents(options).filter((event) => inScope(event.companion));
273
+ const ids = new Set(events.map((event) => event.id));
274
+ const reports = readReports(options).filter((report) =>
275
+ report.eventId ? ids.has(report.eventId) : inScope(report.companion),
276
+ );
277
+ return { events, reports };
278
+ }
279
+
280
+ function findRecord<T>(
281
+ family: Family,
282
+ accept: (value: unknown) => value is T,
283
+ match: (record: T) => boolean,
284
+ homeDir?: string,
285
+ ): T | null {
286
+ let months: string[];
287
+ try {
288
+ months = logMonths(frictionLogDir(homeDir), family);
289
+ } catch {
290
+ return null;
291
+ }
292
+ for (const month of months.toSorted().toReversed()) {
293
+ const found = readMonth(family, month, accept, homeDir).find(match);
294
+ if (found) return found;
295
+ }
296
+ return null;
297
+ }
298
+
299
+ /** The event with this id in any retained month, or null. */
300
+ export function findEvent(id: string, options: { homeDir?: string } = {}): FrictionEvent | null {
301
+ return findRecord("events", isFrictionEvent, (event) => event.id === id, options.homeDir);
302
+ }
303
+
304
+ /** The newest event with this fingerprint in any retained month, or null. */
305
+ export function findFingerprint(
306
+ fingerprint: string,
307
+ options: { homeDir?: string } = {},
308
+ ): FrictionEvent | null {
309
+ return findRecord(
310
+ "events",
311
+ isFrictionEvent,
312
+ (event) => event.fingerprint === fingerprint,
313
+ options.homeDir,
314
+ );
315
+ }
316
+
317
+ /** The report with this id in any retained month, or null. */
318
+ export function findReport(id: string, options: { homeDir?: string } = {}): FrictionReport | null {
319
+ return findRecord("reports", isFrictionReport, (report) => report.id === id, options.homeDir);
320
+ }
321
+
322
+ /**
323
+ * The ids of every report in the retained months; null when a file could not be read or a line
324
+ * not parsed, since a report missing from the set may then still exist.
325
+ */
326
+ export function readReportIds(options: { homeDir?: string } = {}): Set<string> | null {
327
+ let months: string[];
328
+ try {
329
+ months = logMonths(frictionLogDir(options.homeDir), "reports");
330
+ } catch (error) {
331
+ return isMissing(error) ? new Set() : null;
332
+ }
333
+ const ids = new Set<string>();
334
+ for (const month of months) {
335
+ const { records, complete } = scanMonth("reports", month, isFrictionReport, options.homeDir);
336
+ if (!complete) return null;
337
+ for (const report of records) ids.add(report.id);
338
+ }
339
+ return ids;
340
+ }
341
+
342
+ /** Whether no earlier line of the event's month holds the same session and fingerprint. */
343
+ export function firstInSession(event: FrictionEvent, options: { homeDir?: string } = {}): boolean {
344
+ const month = readMonth("events", monthOf(new Date(event.at)), isFrictionEvent, options.homeDir);
345
+ for (const recorded of month) {
346
+ if (recorded.id === event.id) return true;
347
+ if (recorded.sessionId === event.sessionId && recorded.fingerprint === event.fingerprint) {
348
+ return false;
349
+ }
350
+ }
351
+ return true;
352
+ }