@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
@@ -0,0 +1,42 @@
1
+ import { FRAMEWORK_NAME } from "../../framework";
2
+ import {
3
+ parseFingerprint,
4
+ type FrictionCheck,
5
+ type ToolKind,
6
+ } from "../../runtime/friction-fingerprint";
7
+
8
+ const CHECKS: Record<FrictionCheck, string> = {
9
+ secret: "The secret check",
10
+ attribution: "The attribution check",
11
+ artifact: "The artifact check",
12
+ fork: "The fork check",
13
+ };
14
+
15
+ const TOOL_KINDS: Record<ToolKind, string> = {
16
+ read: "a file read",
17
+ write: "a file write",
18
+ shell: "a shell command",
19
+ search: "a search",
20
+ other: "a tool call",
21
+ };
22
+
23
+ /** One plain sentence for a fingerprint; one it does not know is returned unchanged. */
24
+ export function describeFingerprint(fingerprint: string): string {
25
+ const { form, name, rest } = parseFingerprint(fingerprint);
26
+ if (
27
+ form === "refusal" &&
28
+ name !== undefined &&
29
+ rest.length === 1 &&
30
+ Object.hasOwn(CHECKS, name) &&
31
+ Object.hasOwn(TOOL_KINDS, rest[0])
32
+ )
33
+ return `${CHECKS[name as FrictionCheck]} refused ${TOOL_KINDS[rest[0] as ToolKind]}`;
34
+ if (form === "command" && rest.length > 0) {
35
+ const exitCode = rest.at(-1)!;
36
+ if (/^\d+$/.test(exitCode)) {
37
+ const words = [name, ...rest.slice(0, -1)].join(":");
38
+ return `${[FRAMEWORK_NAME, words].join(" ").trim()} failed with exit code ${exitCode}`;
39
+ }
40
+ }
41
+ return fingerprint;
42
+ }
@@ -0,0 +1,60 @@
1
+ import { parseFingerprint } from "../../runtime/friction-fingerprint";
2
+ import type { FrictionEvent } from "../../runtime/friction-log";
3
+ import type { SecretFinding } from "../../runtime/secret-scan";
4
+
5
+ export const TEXT_LIMIT = 1_000;
6
+
7
+ export const cut = (text: string) => text.slice(0, TEXT_LIMIT);
8
+
9
+ /** The subject type a report on the event takes: `hook` for a refusal, `command` otherwise. */
10
+ export function eventSubjectType(event: Pick<FrictionEvent, "fingerprint">): "hook" | "command" {
11
+ return parseFingerprint(event.fingerprint).form === "refusal" ? "hook" : "command";
12
+ }
13
+
14
+ /** `hook:<check>` for a refusal, `command:<command words>` for a failed command. */
15
+ export function eventSubject(event: Pick<FrictionEvent, "fingerprint">): string {
16
+ return `${eventSubjectType(event)}:${parseFingerprint(event.fingerprint).name}`;
17
+ }
18
+
19
+ /** A refusal is an answer to the caller, not a failure: it carries a stable code. */
20
+ export class FrictionRefusal extends Error {
21
+ constructor(
22
+ readonly code: string,
23
+ message: string,
24
+ ) {
25
+ super(message);
26
+ }
27
+ }
28
+
29
+ export type SecretScan = (filePath: string, content: string) => Promise<SecretFinding[]>;
30
+
31
+ /** The scanner needs a file name; friction text is scanned as a companion write would be. */
32
+ const SCAN_NAME = "friction-report.md";
33
+
34
+ /**
35
+ * Refuses text the secret scanner flags, naming its rules and never the text. The scanner
36
+ * loads only here, so a caller without text never pays for it.
37
+ */
38
+ export async function refuseSecrets(
39
+ what: string,
40
+ fields: (string | null)[],
41
+ scan?: SecretScan,
42
+ ): Promise<void> {
43
+ let findings: SecretFinding[];
44
+ try {
45
+ const scanContent = scan ?? (await import("../../runtime/secret-scan")).scanContent;
46
+ findings = await scanContent(SCAN_NAME, fields.filter((field) => field !== null).join("\n"));
47
+ } catch {
48
+ throw new FrictionRefusal(
49
+ "scan-failed",
50
+ `${what} could not be scanned for secrets; nothing was recorded.`,
51
+ );
52
+ }
53
+ if (findings.length > 0) {
54
+ const rules = [...new Set(findings.map((finding) => finding.ruleId))];
55
+ throw new FrictionRefusal(
56
+ "secret",
57
+ `${what} holds a secret (${rules.join(", ")}); nothing was recorded. Replace the value with a placeholder or the variable name.`,
58
+ );
59
+ }
60
+ }
@@ -0,0 +1,156 @@
1
+ import { findEvent, findFingerprint, findReport, readReportIds } from "../../runtime/friction-log";
2
+ import {
3
+ FrictionStateFileError,
4
+ type FrictionStatesFile,
5
+ readFrictionStates,
6
+ updateFrictionStates,
7
+ } from "../../runtime/friction-state";
8
+ import type {
9
+ FrictionState,
10
+ FrictionStateOrigin,
11
+ MarkState,
12
+ } from "../../runtime/friction-vocabulary";
13
+ import type { LockOptions } from "../../runtime/session-registry";
14
+ import { cut, FrictionRefusal, refuseSecrets, type SecretScan } from "./fields";
15
+
16
+ export interface MarkInput {
17
+ note?: string;
18
+ link?: string;
19
+ by: FrictionStateOrigin;
20
+ }
21
+
22
+ export interface MarkDeps {
23
+ homeDir?: string;
24
+ now?: Date;
25
+ scan?: SecretScan;
26
+ lock?: LockOptions;
27
+ }
28
+
29
+ export type MarkResult =
30
+ | { ok: true; target: string; state: FrictionState | null }
31
+ | { ok: false; code: string; reason: string };
32
+
33
+ const REPORT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
34
+
35
+ const unknownTarget = (target: string) =>
36
+ new FrictionRefusal(
37
+ "unknown-target",
38
+ `${target} is no recorded fingerprint and no Free Report; nothing was changed.`,
39
+ );
40
+
41
+ const textOrNull = (text: string | undefined) => (text?.trim() ? cut(text) : null);
42
+
43
+ function checkLink(link: string | null, state: MarkState): void {
44
+ if (link === null) return;
45
+ if (state !== "reported") {
46
+ throw new FrictionRefusal(
47
+ "link-needs-reported",
48
+ "A link is kept only with the state reported (--state reported); nothing was changed.",
49
+ );
50
+ }
51
+ let protocol: string;
52
+ try {
53
+ protocol = new URL(link).protocol;
54
+ } catch {
55
+ protocol = "";
56
+ }
57
+ if (protocol !== "http:" && protocol !== "https:") {
58
+ throw new FrictionRefusal(
59
+ "invalid-link",
60
+ "The link must be an http or https URL; nothing was changed.",
61
+ );
62
+ }
63
+ }
64
+
65
+ function resolveTarget(
66
+ target: string,
67
+ known: { fingerprints: object; reports: object },
68
+ homeDir?: string,
69
+ ): "fingerprints" | "reports" {
70
+ if (Object.hasOwn(known.fingerprints, target)) return "fingerprints";
71
+ if (Object.hasOwn(known.reports, target)) return "reports";
72
+ if (!REPORT_ID.test(target)) {
73
+ if (!findFingerprint(target, { homeDir })) throw unknownTarget(target);
74
+ return "fingerprints";
75
+ }
76
+ const report = findReport(target, { homeDir });
77
+ if (!report) throw unknownTarget(target);
78
+ if (report.eventId) {
79
+ const event = findEvent(report.eventId, { homeDir });
80
+ throw new FrictionRefusal(
81
+ "report-on-event",
82
+ `${target} is a report on an event; it follows the state of its fingerprint${event ? ` ${event.fingerprint}` : ""}. Mark that fingerprint instead; nothing was changed.`,
83
+ );
84
+ }
85
+ return "reports";
86
+ }
87
+
88
+ function forgetExpiredReports(
89
+ states: FrictionStatesFile,
90
+ idsReadBeforeScan: string[],
91
+ retained: Set<string>,
92
+ ): void {
93
+ for (const id of idsReadBeforeScan) {
94
+ if (!retained.has(id)) delete states.reports[id];
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Sets or, with `open`, clears the Friction State of a fingerprint or a Free Report. The checks
100
+ * live here once for every caller; the Friction Log is never written.
101
+ */
102
+ export async function markFriction(
103
+ target: string,
104
+ state: MarkState,
105
+ input: MarkInput,
106
+ deps: MarkDeps = {},
107
+ ): Promise<MarkResult> {
108
+ try {
109
+ const note = textOrNull(input.note);
110
+ const link = textOrNull(input.link);
111
+ checkLink(link, state);
112
+ const known = readFrictionStates(deps.homeDir);
113
+ const family = resolveTarget(target, known, deps.homeDir);
114
+ if (note !== null || link !== null) await refuseSecrets("The mark", [note, link], deps.scan);
115
+ const retained =
116
+ Object.keys(known.reports).length > 0 ? readReportIds({ homeDir: deps.homeDir }) : null;
117
+ if (family === "reports" && retained && !retained.has(target)) {
118
+ throw unknownTarget(target);
119
+ }
120
+ const next: FrictionState | null =
121
+ state === "open"
122
+ ? null
123
+ : {
124
+ state,
125
+ at: (deps.now ?? new Date()).toISOString(),
126
+ by: input.by,
127
+ note,
128
+ link,
129
+ };
130
+ await updateFrictionStates(
131
+ (states) => {
132
+ if (retained) forgetExpiredReports(states, Object.keys(known.reports), retained);
133
+ if (next) states[family][target] = next;
134
+ else delete states[family][target];
135
+ },
136
+ { homeDir: deps.homeDir, lock: deps.lock },
137
+ );
138
+ return { ok: true, target, state: next };
139
+ } catch (error) {
140
+ if (error instanceof FrictionRefusal) {
141
+ return { ok: false, code: error.code, reason: error.message };
142
+ }
143
+ if (error instanceof FrictionStateFileError) {
144
+ return {
145
+ ok: false,
146
+ code: "state-file-damaged",
147
+ reason: `${error.message}; it was left unchanged and nothing was marked. Repair or delete it to mark again.`,
148
+ };
149
+ }
150
+ return {
151
+ ok: false,
152
+ code: "write-failed",
153
+ reason: `The Friction State could not be written: ${error instanceof Error ? error.message : String(error)}`,
154
+ };
155
+ }
156
+ }
@@ -0,0 +1,67 @@
1
+ import type { FrictionReport } from "../../../runtime/friction-log";
2
+ import { FRICTION_RETENTION_DAYS } from "../../../runtime/friction-retention";
3
+ import type { FrictionState, SubjectType } from "../../../runtime/friction-vocabulary";
4
+
5
+ export const FRICTION_VIEW_DAYS = [7, 30, FRICTION_RETENTION_DAYS] as const;
6
+ export type FrictionViewDays = (typeof FRICTION_VIEW_DAYS)[number];
7
+
8
+ /** The period a value names, as a number or its text; `undefined` for any other. */
9
+ export function frictionViewDays(value: unknown): FrictionViewDays | undefined {
10
+ return FRICTION_VIEW_DAYS.find((days) => String(days) === String(value));
11
+ }
12
+
13
+ /** A fingerprint's Friction State with what later events tell about it, derived on read. */
14
+ export interface FrictionGroupState extends FrictionState {
15
+ /** Events of the period later than the mark. */
16
+ eventsSince: number;
17
+ /** `fixed`, yet recorded again after the mark. */
18
+ reopened: boolean;
19
+ }
20
+
21
+ export type FrictionItemState = FrictionState &
22
+ Partial<Pick<FrictionGroupState, "eventsSince" | "reopened">>;
23
+
24
+ export interface FrictionGroup {
25
+ fingerprint: string;
26
+ title: string;
27
+ /** The subject type a report on its events takes: `hook` for a refusal, `command` otherwise. */
28
+ subjectType: SubjectType;
29
+ events: number;
30
+ sessions: number;
31
+ /** The highest event count within one session. */
32
+ maxPerSession: number;
33
+ firstSeen: string;
34
+ lastSeen: string;
35
+ /** Mate version → event count. */
36
+ versions: Record<string, number>;
37
+ /** Companion path → event count. */
38
+ companions: Record<string, number>;
39
+ /** Path a refused call named → event count. */
40
+ paths: Record<string, number>;
41
+ /** Flag a failed command carried → event count. */
42
+ flags: Record<string, number>;
43
+ /** Reports on the group's events, newest first. */
44
+ reports: FrictionReport[];
45
+ state: FrictionGroupState | null;
46
+ /** Unmarked or reopened. */
47
+ open: boolean;
48
+ }
49
+
50
+ export interface FrictionFreeReport extends FrictionReport {
51
+ /** `null` for a subject of no known type. */
52
+ subjectType: SubjectType | null;
53
+ state: FrictionState | null;
54
+ open: boolean;
55
+ }
56
+
57
+ /** The Friction View of a scope and period; `mate friction list --json` and Studio carry it. */
58
+ export interface FrictionView {
59
+ recording: boolean;
60
+ days: number;
61
+ events: number;
62
+ sessions: number;
63
+ /** Most repeated within one session first, then by event count. */
64
+ groups: FrictionGroup[];
65
+ /** Newest first. */
66
+ freeReports: FrictionFreeReport[];
67
+ }
@@ -0,0 +1,136 @@
1
+ import {
2
+ readFriction,
3
+ type FrictionEvent,
4
+ type FrictionReport,
5
+ type FrictionScope,
6
+ } from "../../../runtime/friction-log";
7
+ import { readFrictionStates } from "../../../runtime/friction-state";
8
+ import { readFrictionSwitch } from "../../../runtime/friction-switch";
9
+ import { subjectTypeOf, type FrictionState } from "../../../runtime/friction-vocabulary";
10
+ import { describeFingerprint } from "../describe";
11
+ import { eventSubjectType } from "../fields";
12
+ import type { FrictionGroup, FrictionGroupState, FrictionView } from "./model";
13
+
14
+ // The one reader that joins the Friction Log with the Friction States (ADR-026); reads only.
15
+
16
+ interface FrictionWindow {
17
+ days: number;
18
+ homeDir?: string;
19
+ now?: Date;
20
+ }
21
+
22
+ export interface FrictionRecords {
23
+ events: FrictionEvent[];
24
+ /** The reports on those events wherever they were made, and the scope's Free Reports. */
25
+ reports: FrictionReport[];
26
+ /** The Friction States of the fingerprints and Free Reports in the records, and no other. */
27
+ states: {
28
+ fingerprints: Record<string, FrictionGroupState>;
29
+ reports: Record<string, FrictionState>;
30
+ };
31
+ }
32
+
33
+ function groupState(state: FrictionState, times: string[]): FrictionGroupState {
34
+ const markedAt = Date.parse(state.at);
35
+ const eventsSince = times.filter((at) => Date.parse(at) > markedAt).length;
36
+ return { ...state, eventsSince, reopened: state.state === "fixed" && eventsSince > 0 };
37
+ }
38
+
39
+ const byFingerprint = (events: FrictionEvent[]) =>
40
+ Map.groupBy(events, (event) => event.fingerprint);
41
+
42
+ export function readFrictionRecords(scope: FrictionScope, window: FrictionWindow): FrictionRecords {
43
+ const { events, reports } = readFriction(scope, {
44
+ sinceDays: window.days,
45
+ homeDir: window.homeDir,
46
+ now: window.now,
47
+ });
48
+ const stored = readFrictionStates(window.homeDir);
49
+ const fingerprints: Record<string, FrictionGroupState> = {};
50
+ for (const [fingerprint, grouped] of byFingerprint(events)) {
51
+ const state = stored.fingerprints[fingerprint];
52
+ if (state) {
53
+ fingerprints[fingerprint] = groupState(
54
+ state,
55
+ grouped.map((event) => event.at),
56
+ );
57
+ }
58
+ }
59
+ const freeStates: Record<string, FrictionState> = {};
60
+ for (const report of reports) {
61
+ const state = report.eventId ? undefined : stored.reports[report.id];
62
+ if (state) freeStates[report.id] = state;
63
+ }
64
+ return { events, reports, states: { fingerprints, reports: freeStates } };
65
+ }
66
+
67
+ const newestFirst = (reports: FrictionReport[]) =>
68
+ reports.toSorted((a, b) => b.at.localeCompare(a.at));
69
+
70
+ const strings = (value: unknown): string[] =>
71
+ Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
72
+
73
+ function tally(counts: Record<string, number>, names: string[]): void {
74
+ for (const name of new Set(names)) counts[name] = (counts[name] ?? 0) + 1;
75
+ }
76
+
77
+ function toGroup(
78
+ fingerprint: string,
79
+ grouped: FrictionEvent[],
80
+ reportsByEvent: Map<string | null, FrictionReport[]>,
81
+ state: FrictionGroupState | undefined,
82
+ ): FrictionGroup {
83
+ const perSession = new Map<string, number>();
84
+ const versions: Record<string, number> = {};
85
+ const companions: Record<string, number> = {};
86
+ const paths: Record<string, number> = {};
87
+ const flags: Record<string, number> = {};
88
+ for (const event of grouped) {
89
+ perSession.set(event.sessionId, (perSession.get(event.sessionId) ?? 0) + 1);
90
+ versions[event.mateVersion] = (versions[event.mateVersion] ?? 0) + 1;
91
+ companions[event.companion] = (companions[event.companion] ?? 0) + 1;
92
+ tally(paths, strings(event.detail.paths));
93
+ tally(flags, strings(event.detail.flags));
94
+ }
95
+ const times = grouped.map((event) => event.at).toSorted();
96
+ return {
97
+ fingerprint,
98
+ title: describeFingerprint(fingerprint),
99
+ subjectType: eventSubjectType({ fingerprint }),
100
+ events: grouped.length,
101
+ sessions: perSession.size,
102
+ maxPerSession: Math.max(...perSession.values()),
103
+ firstSeen: times[0],
104
+ lastSeen: times[times.length - 1],
105
+ versions,
106
+ companions,
107
+ paths,
108
+ flags,
109
+ reports: newestFirst(grouped.flatMap((event) => reportsByEvent.get(event.id) ?? [])),
110
+ state: state ?? null,
111
+ open: !state || state.reopened,
112
+ };
113
+ }
114
+
115
+ export function readFrictionView(scope: FrictionScope, window: FrictionWindow): FrictionView {
116
+ const { events, reports, states } = readFrictionRecords(scope, window);
117
+ const reportsByEvent = Map.groupBy(
118
+ reports.filter((report) => report.eventId),
119
+ (report) => report.eventId,
120
+ );
121
+ const groups = [...byFingerprint(events)].map(([fingerprint, grouped]) =>
122
+ toGroup(fingerprint, grouped, reportsByEvent, states.fingerprints[fingerprint]),
123
+ );
124
+ groups.sort((a, b) => b.maxPerSession - a.maxPerSession || b.events - a.events);
125
+ return {
126
+ recording: readFrictionSwitch(window.homeDir),
127
+ days: window.days,
128
+ events: events.length,
129
+ sessions: new Set(events.map((event) => event.sessionId)).size,
130
+ groups,
131
+ freeReports: newestFirst(reports.filter((report) => !report.eventId)).map((report) => {
132
+ const state = states.reports[report.id] ?? null;
133
+ return { ...report, subjectType: subjectTypeOf(report.subject), state, open: !state };
134
+ }),
135
+ };
136
+ }
@@ -0,0 +1,54 @@
1
+ import {
2
+ SUBJECT_TYPES,
3
+ type ReportKind,
4
+ type StateFilter,
5
+ type SubjectType,
6
+ } from "../../../runtime/friction-vocabulary";
7
+ import type { FrictionFreeReport, FrictionGroup, FrictionView } from "./model";
8
+
9
+ export interface FrictionFilters {
10
+ state: StateFilter;
11
+ /** Absent means every type. */
12
+ type?: SubjectType;
13
+ /** Narrows Free Reports only; absent means every kind. */
14
+ kind?: ReportKind;
15
+ }
16
+
17
+ export interface FrictionShown {
18
+ groups: FrictionGroup[];
19
+ freeReports: FrictionFreeReport[];
20
+ /** Items of the period the filters leave out. */
21
+ hidden: number;
22
+ /** The subject types present in the period, in vocabulary order. */
23
+ types: SubjectType[];
24
+ /** The type filtered on; a type absent from the period reads as every type. */
25
+ type?: SubjectType;
26
+ }
27
+
28
+ /** The Friction Items the filters show, in the view's order. */
29
+ export function selectFriction(
30
+ view: Pick<FrictionView, "groups" | "freeReports">,
31
+ filters: FrictionFilters,
32
+ ): FrictionShown {
33
+ const present = new Set<SubjectType | null>([
34
+ ...view.groups.map((group) => group.subjectType),
35
+ ...view.freeReports.map((report) => report.subjectType),
36
+ ]);
37
+ const types = SUBJECT_TYPES.filter((type) => present.has(type));
38
+ const type = types.find((known) => known === filters.type);
39
+ const shown = (item: { open: boolean; subjectType: SubjectType | null }) =>
40
+ (filters.state === "all" || item.open === (filters.state === "open")) &&
41
+ (!type || item.subjectType === type);
42
+ const groups = view.groups.filter(shown);
43
+ const freeReports = view.freeReports.filter(
44
+ (report) => shown(report) && (!filters.kind || report.kind === filters.kind),
45
+ );
46
+ const total = view.groups.length + view.freeReports.length;
47
+ return {
48
+ groups,
49
+ freeReports,
50
+ hidden: total - groups.length - freeReports.length,
51
+ types,
52
+ type,
53
+ };
54
+ }
@@ -14,6 +14,7 @@ import {
14
14
  } from "../../../runtime/claude-delivery-plan";
15
15
  import { hookGroupKey, type ClaudeHookGroup } from "../../../runtime/claude-hook-group";
16
16
  import { MATE_ENV } from "../../../runtime/env-names";
17
+ import { readFrictionSwitch } from "../../../runtime/friction-switch";
17
18
  import { SESSION_ORIGIN_ENV } from "../../../runtime/session-registry";
18
19
  import { resolveSecretPolicy } from "../../../runtime/policy";
19
20
  import { managedSessionKind } from "../../../runtime/session-kind";
@@ -331,10 +332,10 @@ export class ClaudeAdapter extends LaunchAdapter<ClaudeLaunchContext> {
331
332
  const mcpConfigArgs =
332
333
  plan.mcp === "mcp-config" && mcpConfigPath ? ["--mcp-config", mcpConfigPath] : [];
333
334
 
334
- const guidance = buildCompanionGuidance({
335
- ...context,
336
- secretGuardrails: resolveSecretPolicy(context.companionPath).guardrails,
337
- });
335
+ const guidance = buildCompanionGuidance(
336
+ { ...context, secretGuardrails: resolveSecretPolicy(context.companionPath).guardrails },
337
+ { friction: readFrictionSwitch() },
338
+ );
338
339
  const children = context.repository ? umbrellaChildrenBlock(context.repository.path) : "";
339
340
  const { args: passthrough, prompts, boundary } = liftAppendedPrompts(args);
340
341
  const promptArgs = [
@@ -5,6 +5,7 @@ const fs = await import("node:fs/promises");
5
5
  const path = await import("node:path");
6
6
 
7
7
  import { MATE_ENV } from "../../../runtime/env";
8
+ import { readFrictionSwitch } from "../../../runtime/friction-switch";
8
9
  import { SESSION_ORIGIN_ENV } from "../../../runtime/session-registry";
9
10
  import { mainCheckoutOf } from "../../../runtime/git-layout";
10
11
  import { OPENCODE_PASSWORD } from "../../../runtime/opencode-server-record";
@@ -172,6 +173,7 @@ export class OpenCodeAdapter extends LaunchAdapter {
172
173
  return buildOpenCodeGuidance(context.capabilities, {
173
174
  companionScoped: !context.repository,
174
175
  secretGuardrails: resolveSecretPolicy(context.companionPath).guardrails,
176
+ friction: readFrictionSwitch(),
175
177
  ...declaredGuidance(context.companionPath),
176
178
  });
177
179
  }
@@ -7,7 +7,7 @@ import {
7
7
  type CompanionResolutionResult,
8
8
  findRepoLocalLinkedRepository,
9
9
  } from "./repository-link";
10
- import { ConfigStore, mergeWithDefaults } from "./config-store";
10
+ import { ConfigStore, defaultConfig, mergeWithDefaults } from "./config-store";
11
11
  import { GlobalConfigStore } from "./global-config-store";
12
12
  import type { FrameworkConfig, LinkedRepository } from "./types";
13
13
 
@@ -32,6 +32,8 @@ export interface RootContext {
32
32
 
33
33
  export interface RootContextDeps {
34
34
  globalConfigStore?: GlobalConfigStore;
35
+ /** `false` resolves without repairing the repo-local registry. */
36
+ write?: boolean;
35
37
  }
36
38
 
37
39
  const emptyResolution = (): CompanionResolutionResult => ({
@@ -44,8 +46,22 @@ function kindForConfig(config: FrameworkConfig): Exclude<RootKind, "core"> {
44
46
  return config.type === "hub" ? "hub" : config.type === "working" ? "working" : "companion";
45
47
  }
46
48
 
47
- async function loadRootConfig(rootPath: string): Promise<FrameworkConfig> {
49
+ async function loadRootConfig(
50
+ rootPath: string,
51
+ write?: boolean,
52
+ failures: CompanionResolutionResult["failures"] = [],
53
+ ): Promise<FrameworkConfig> {
48
54
  const configPath = path.join(rootPath, `.${FRAMEWORK_NAME}`, "config", "framework.yaml");
55
+ const missing =
56
+ write === false &&
57
+ (await fs.access(configPath).then(
58
+ () => false,
59
+ (error: NodeJS.ErrnoException) => error.code === "ENOENT",
60
+ ));
61
+ if (missing) {
62
+ failures.push({ companionPath: rootPath, message: `${configPath} is missing.` });
63
+ return mergeWithDefaults(defaultConfig());
64
+ }
49
65
  return mergeWithDefaults(await new ConfigStore(configPath).load());
50
66
  }
51
67
 
@@ -59,7 +75,8 @@ export async function resolveRootContext(
59
75
  const envRootPath = process.env.MATE_ARTIFACT_PATH;
60
76
  if (envRootPath) {
61
77
  const rootPath = path.resolve(envRootPath);
62
- const config = await loadRootConfig(rootPath);
78
+ const resolution = emptyResolution();
79
+ const config = await loadRootConfig(rootPath, deps.write, resolution.failures);
63
80
  return {
64
81
  kind: kindForConfig(config),
65
82
  origin: "env",
@@ -67,15 +84,15 @@ export async function resolveRootContext(
67
84
  config,
68
85
  repositoryId: process.env.MATE_REPO_ID ?? linkedRepository?.id,
69
86
  linkedRepository,
70
- resolution: emptyResolution(),
87
+ resolution,
71
88
  };
72
89
  }
73
90
 
74
91
  const resolver = new CompanionResolver(deps.globalConfigStore ?? new GlobalConfigStore());
75
- const resolution = await resolver.resolveWithDiagnostics(resolvedCwd);
92
+ const resolution = await resolver.resolveWithDiagnostics(resolvedCwd, { write: deps.write });
76
93
  if (resolution.match) {
77
94
  const rootPath = resolution.match.companionPath;
78
- const config = await loadRootConfig(rootPath);
95
+ const config = await loadRootConfig(rootPath, deps.write, resolution.failures);
79
96
  return {
80
97
  kind: kindForConfig(config),
81
98
  origin: "registry",