gitlab-labkit 5.6.0 → 5.7.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fb00f476a5fed0be71839727d4fb5d8230f773831c8c8cca40ff8090c76cb2c5
4
- data.tar.gz: c382bf0eed9e55b283eb90c3956a00c8dbf73ad5819fb22e8dd6a1be931fd9ff
3
+ metadata.gz: f2d9d587afe49d99a2ada5a8757230d69024a1085009f1e65c29ac97aa005e98
4
+ data.tar.gz: 35e55c1e1f9aef6836736e6917cffe4813aa37655eebf5534893f9b7b232fb89
5
5
  SHA512:
6
- metadata.gz: 5932210330aa7c8c4413de43f8ae710508658846c89f1b7b74e1d8d36af564b61034988a6248bf9795d6343602d4b1579d6a9aff48795cda1163c545377932b9
7
- data.tar.gz: ddc501d350806e384f122f152f6ceb7066487bc4f41078341f1ae13373631adf52a1f5cd427a69e879482cf3dc1dff75bbfe7cd57dd1237094c595e615acc591
6
+ metadata.gz: 83a9378e749aa4c04cf05cca872fffabe8945802b169c996aba579b43b73e582d98dca6c37b31c82098fe3edda41932ddc81813010ab278e2df7569812c7926e
7
+ data.tar.gz: 5b00ebd19184fbfaec05c1cdf40de93b74a70c0a7aa2b167213425debada2ea6708b61874d4ad23a9de40c950724b47da599d37daf0116d323ed8b4db76a6d23
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env bash
2
+ # PostToolUse hook: validate a just-edited file against this repo's pre-commit rules.
3
+ #
4
+ # Runs `pre-commit run --files <file>` on the file that Edit/Write/MultiEdit
5
+ # touched. On failure it prints the output to stderr and exits 2, which feeds the
6
+ # result back to Claude so it can fix the issue. A clean run exits 0 silently.
7
+ set -euo pipefail
8
+ IFS=$'\n\t'
9
+
10
+ # no-commit-to-branch guards the branch, not file content, and would fire
11
+ # spuriously (e.g. on jj's detached HEAD). It is irrelevant to file validation.
12
+ export SKIP="no-commit-to-branch"
13
+
14
+ # Run through `mise exec` so mise-managed tools that the hooks rely on
15
+ # (pre-commit, jsonnet-tool, shfmt, ...) are on PATH, matching a normal
16
+ # interactive shell.
17
+ if ! command -v mise >/dev/null 2>&1; then
18
+ echo "pre-commit validation hook requires mise to run." >&2
19
+ exit 1
20
+ fi
21
+
22
+ run() { mise exec -- "$@"; }
23
+
24
+ repo_root="$(git rev-parse --show-toplevel 2>/dev/null)" || exit 0
25
+
26
+ input="$(cat)"
27
+ file="$(printf '%s' "$input" | mise exec jq@1.8 -- jq -r '.tool_input.file_path // empty')"
28
+ [[ -z $file ]] && exit 0
29
+
30
+ # Only validate files that live inside this repository.
31
+ case "$file" in
32
+ "$repo_root"/*) ;;
33
+ *) exit 0 ;;
34
+ esac
35
+
36
+ if ! output="$(cd "$repo_root" && run pre-commit run --files "$file" 2>&1)"; then
37
+ {
38
+ echo "pre-commit reported issues on ${file#"$repo_root"/}:"
39
+ echo
40
+ echo "$output"
41
+ echo
42
+ echo "Re-read the file (hooks such as trailing-whitespace, shfmt, and"
43
+ echo "generate may have rewritten it) and fix any remaining problems."
44
+ } >&2
45
+ exit 2
46
+ fi
47
+
48
+ exit 0
@@ -0,0 +1,15 @@
1
+ {
2
+ "hooks": {
3
+ "PostToolUse": [
4
+ {
5
+ "matcher": "Edit|Write|MultiEdit",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/precommit-validate.sh\""
10
+ }
11
+ ]
12
+ }
13
+ ]
14
+ }
15
+ }
data/.copier-answers.yml CHANGED
@@ -3,7 +3,7 @@
3
3
  # See the project for instructions on how to update the project
4
4
  #
5
5
  # Changes here will be overwritten by Copier; NEVER EDIT MANUALLY
6
- _commit: v1.60.0
6
+ _commit: v1.87.1
7
7
  _src_path: https://gitlab.com/gitlab-com/gl-infra/common-template-copier.git
8
8
  ee_licensed: false
9
9
  gitlab_namespace: gitlab-org/ruby/gems
@@ -17,5 +17,6 @@ release_platform: false
17
17
  ruby: true
18
18
  rubygem: true
19
19
  rust: false
20
+ scaffold_target: repo
20
21
  terraform: false
21
22
  truncated_tags: true
data/.gitignore CHANGED
@@ -2,5 +2,4 @@ Gemfile.lock
2
2
  *.gem
3
3
  node_modules
4
4
  .bundle
5
- /.env.sh
6
5
  .idea/
data/.gitlab/CODEOWNERS CHANGED
@@ -1 +1 @@
1
- * @reprazent @mkaeppler @ayufan @hmerscher @sankalp_gl @hardikgala @nindurkar @ashs2
1
+ * @mkaeppler @ayufan @hmerscher @sankalp_gl @hardikgala @nindurkar @ashs2
@@ -7,22 +7,22 @@
7
7
  image: registry.gitlab.com/gitlab-com/gl-infra/common-ci-tasks-images/duo-workflow-sandbox:latest
8
8
 
9
9
  setup_script:
10
- # Keep mise's data + cache inside the project dir so the `cache:` block below
11
- # can capture them (caching only reliably covers paths under the project dir).
12
- - export MISE_DATA_DIR="${CI_PROJECT_DIR}/.cache/mise/data"
13
- - export MISE_CACHE_DIR="${CI_PROJECT_DIR}/.cache/mise/cache"
14
- - mise trust --yes
15
- - mise install --yes
10
+ # duo-workflow-setup (baked into the image) exports some variables as
11
+ # `export KEY=VALUE` lines on stdout, which we `eval` into the flow's shell.
12
+ - eval "$(/usr/local/bin/duo-workflow-setup)"
16
13
 
17
14
  cache:
18
- # Re-use installed tools as long as the version pins are unchanged.
15
+ # Re-use installed tools and primed pre-commit hooks as long as the version
16
+ # pins / hook config are unchanged.
19
17
  key:
20
18
  files:
21
19
  - .tool-versions
22
20
  - .mise.toml
21
+ - .pre-commit-config.yaml
23
22
  paths:
24
23
  - .cache/mise/data
25
24
  - .cache/mise/cache
25
+ - .cache/pre-commit
26
26
 
27
27
  network_policy:
28
28
  # Allow the Sandbox Runtime's recommended allowlist (GitLab, package
data/.gitlab-ci.yml CHANGED
@@ -19,13 +19,27 @@ include:
19
19
  # It includes standard checks, gitlab-scanners, validations and release processes
20
20
  # common to all projects using this template library.
21
21
  # see https://gitlab.com/gitlab-com/gl-infra/common-ci-tasks/-/blob/main/templates/standard.md
22
- - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/standard-build@v5.24
22
+ - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/standard-build@v5.46
23
23
 
24
24
  # Runs rspec tests and rubocop on the project
25
25
  # see https://gitlab.com/gitlab-com/gl-infra/common-ci-tasks/-/blob/main/templates/ruby.md
26
- - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/ruby-build@v5.24
26
+ - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/ruby-build@v5.46
27
27
 
28
- - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/danger@v5.24
28
+ - component: $CI_SERVER_FQDN/gitlab-com/gl-infra/common-ci-tasks/danger@v5.46
29
+
30
+ # danger-review reads its token from Vault, which the community fork has no
31
+ # access to, so it fails on merge requests from the fork. Let it fail for those;
32
+ # the second rule is the component's own. See
33
+ # https://gitlab.com/gitlab-org/labkit/-/work_items/171
34
+ danger-review:
35
+ rules:
36
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_PATH == "gitlab-community/gitlab-org/ruby/gems/labkit-ruby"
37
+ exists:
38
+ - Dangerfile
39
+ allow_failure: true
40
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
41
+ exists:
42
+ - Dangerfile
29
43
 
30
44
  # Attach a redis service to the rspec job from common-ci-tasks/ruby-build.
31
45
  # GitLab merges keys when a local job has the same name as an included one,
data/.mise.toml CHANGED
@@ -7,6 +7,9 @@ legacy_version_file = false
7
7
  # OpenSSL and sidesteps it. This becomes mise's default in 2026.8.0.
8
8
  ruby.compile = false
9
9
 
10
+ # Disable sending anonymous download statistics to mise-versions.jdx.dev.
11
+ use_versions_host_track = false
12
+
10
13
  [tools]
11
14
  # Please continue to use `.tool-versions` to specify tool versions, rather than adding them directly here.
12
15
 
@@ -0,0 +1,226 @@
1
+ import type { Hooks, PluginModule } from "@opencode-ai/plugin";
2
+ import type { Plugin } from "@opencode/plugin";
3
+ import { execFile, spawn } from "node:child_process";
4
+ import { existsSync } from "node:fs";
5
+ import { isAbsolute, join, resolve } from "node:path";
6
+
7
+ /**
8
+ * precommit-validate plugin
9
+ *
10
+ * OpenCode equivalent of the Claude Code PostToolUse hook defined in
11
+ * `.claude/hooks/precommit-validate.sh` (wired up by `.claude/settings.json`).
12
+ *
13
+ * After the agent edits or writes a file, this runs that *same* shell script to
14
+ * validate the file against the repo's pre-commit rules. When pre-commit reports
15
+ * problems, the findings are appended to the tool result so the agent sees them
16
+ * on its next turn and can fix the file. A clean run is silent.
17
+ *
18
+ * The script's exit codes mirror Claude Code's hook contract, so we honour the
19
+ * same distinction here:
20
+ * - 0 = clean or no-op (silent)
21
+ * - 2 = pre-commit reported issues; feed the report back to the model
22
+ * - any other non-zero = non-blocking error (e.g. mise missing); log it for
23
+ * the user but do not nag the model, since it can't fix its environment.
24
+ *
25
+ * The script is reused verbatim: it reads Claude Code's PostToolUse payload on
26
+ * stdin (`{ "tool_input": { "file_path": "..." } }`), so we synthesize that same
27
+ * shape here from OpenCode's tool input.
28
+ *
29
+ * Supports both plugin APIs from one default export, as described in
30
+ * https://opencode.ai/v2/docs/build/plugins/migrate-v1:
31
+ * - OpenCode 2 reads `id` and `setup()` (the `@opencode/plugin` API).
32
+ * - OpenCode 1 (>= 1.18.29) calls `server()` (the `@opencode-ai/plugin` API).
33
+ * Both imports are type-only, so neither OpenCode version needs the other's
34
+ * plugin package installed at runtime. Remove `server()` once V1 is gone.
35
+ *
36
+ * Auto-loaded from `.opencode/plugins/`.
37
+ */
38
+
39
+ const ID = "precommit-validate";
40
+
41
+ const HOOK_SCRIPT = ".claude/hooks/precommit-validate.sh";
42
+
43
+ // OpenCode file-mutating tools, analogous to Claude Code's `Edit|Write|MultiEdit`
44
+ // matcher. V1 and V2 both have `edit` and `write`; patches go through
45
+ // `apply_patch` in V1 and `patch` in V2.
46
+ const FILE_TOOLS = new Set(["apply_patch", "edit", "patch", "write"]);
47
+
48
+ interface HookResult {
49
+ /** Exit code 2: pre-commit findings to feed back to the model. */
50
+ readonly reports: string[];
51
+ /** Any other failure: environment problems to log for the user. */
52
+ readonly warnings: string[];
53
+ }
54
+
55
+ const asRecord = (value: unknown): Record<string, unknown> =>
56
+ value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
57
+
58
+ const asString = (value: unknown): string | undefined => (typeof value === "string" && value ? value : undefined);
59
+
60
+ /**
61
+ * Collect the files a tool call touched from its input and result metadata.
62
+ *
63
+ * Input: V2 `edit`/`write` take `path`; V1 takes `filePath`.
64
+ * Metadata: `files` entries carry `file` in V2 and `filePath` in V1. This is
65
+ * the only source for patch tools, whose input is a single `patchText` blob.
66
+ */
67
+ function touchedFiles(input: unknown, metadata: unknown): Set<string> {
68
+ const args = asRecord(input);
69
+ const files = new Set<string>();
70
+
71
+ const direct = asString(args.path) ?? asString(args.filePath);
72
+ if (direct) files.add(direct);
73
+
74
+ const entries = asRecord(metadata).files;
75
+ for (const entry of Array.isArray(entries) ? entries : []) {
76
+ const file = asRecord(entry);
77
+ // A deleted file has nothing left to validate.
78
+ if (file.status === "deleted" || file.type === "delete") continue;
79
+ const path = asString(file.file) ?? asString(file.filePath);
80
+ if (path) files.add(path);
81
+ }
82
+
83
+ return files;
84
+ }
85
+
86
+ /** Run the shared hook script for one file, feeding the payload on stdin. */
87
+ function runHookScript(
88
+ script: string,
89
+ root: string,
90
+ payload: string,
91
+ signal?: AbortSignal,
92
+ ): Promise<{ code: number | null; stdout: string; stderr: string }> {
93
+ return new Promise((done, fail) => {
94
+ const child = spawn(script, [], { cwd: root, signal, stdio: ["pipe", "pipe", "pipe"] });
95
+ let stdout = "";
96
+ let stderr = "";
97
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));
98
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
99
+ // The script exits early (e.g. mise missing) without reading stdin.
100
+ child.stdin.on("error", () => {});
101
+ child.on("error", fail);
102
+ child.on("close", (code) => done({ code, stdout, stderr }));
103
+ child.stdin.end(payload);
104
+ });
105
+ }
106
+
107
+ /** Validate every touched file and sort the outcomes into reports and warnings. */
108
+ async function validate(root: string, filePaths: Iterable<string>, signal?: AbortSignal): Promise<HookResult> {
109
+ const result: HookResult = { reports: [], warnings: [] };
110
+ const script = join(root, HOOK_SCRIPT);
111
+ // Inert when the shared script is absent (e.g. loaded in another repo).
112
+ if (!existsSync(script)) return result;
113
+
114
+ for (const filePath of filePaths) {
115
+ if (signal?.aborted) break;
116
+ const absolute = isAbsolute(filePath) ? filePath : resolve(root, filePath);
117
+
118
+ // Same JSON shape Claude Code's PostToolUse hook delivers on stdin. The
119
+ // script itself decides whether the file lives inside the repo.
120
+ const payload = JSON.stringify({ tool_input: { file_path: absolute } });
121
+
122
+ let run: Awaited<ReturnType<typeof runHookScript>>;
123
+ try {
124
+ run = await runHookScript(script, root, payload, signal);
125
+ } catch (error) {
126
+ if (signal?.aborted) break; // plugin unloaded mid-run
127
+ result.warnings.push(`pre-commit validation hook failed to start: ${String(error)}`);
128
+ continue;
129
+ }
130
+
131
+ if (run.code === 0) continue; // clean / no-op
132
+
133
+ const report = run.stderr.trim() || run.stdout.trim();
134
+
135
+ if (run.code === 2) {
136
+ // Blocking: pre-commit reported issues. Surface them to the model, the
137
+ // OpenCode equivalent of feeding the hook's stderr back to Claude Code.
138
+ if (report) result.reports.push(report);
139
+ continue;
140
+ }
141
+
142
+ // Non-blocking error (e.g. exit 1 = mise not on PATH). Not something the
143
+ // model can act on, so log it for the user instead of polluting the turn.
144
+ result.warnings.push(report || `pre-commit validation hook exited ${run.code}`);
145
+ }
146
+
147
+ return result;
148
+ }
149
+
150
+ const formatReports = (reports: string[]): string =>
151
+ `<pre-commit-validation>\n${reports.join("\n\n")}\n</pre-commit-validation>`;
152
+
153
+ /** The repository root, so the hook script is found from any subdirectory. */
154
+ function gitToplevel(directory: string): Promise<string> {
155
+ return new Promise((done) => {
156
+ execFile("git", ["rev-parse", "--show-toplevel"], { cwd: directory }, (error, stdout) => {
157
+ done(error ? directory : stdout.trim() || directory);
158
+ });
159
+ });
160
+ }
161
+
162
+ /** OpenCode 2 implementation (`@opencode/plugin`). */
163
+ const v2: Plugin.Plugin = {
164
+ id: ID,
165
+ async setup(ctx) {
166
+ const root = await gitToplevel(ctx.location.directory);
167
+ // Hook events carry no abort signal; stop in-flight runs on unload instead.
168
+ const controller = new AbortController();
169
+
170
+ await ctx.tool.hook("execute.after", async (event) => {
171
+ if (event.status !== "completed") return;
172
+ if (!FILE_TOOLS.has(event.tool)) return;
173
+
174
+ const filePaths = touchedFiles(event.input, event.result.metadata);
175
+ if (filePaths.size === 0) return;
176
+
177
+ const { reports, warnings } = await validate(root, filePaths, controller.signal);
178
+
179
+ for (const warning of warnings) console.warn(`[${ID}] ${warning}`);
180
+
181
+ if (reports.length === 0) return;
182
+
183
+ // Results are read-only: replace the result, appending to its content.
184
+ const text = formatReports(reports);
185
+ const content = event.result.content;
186
+ event.result = {
187
+ ...event.result,
188
+ content:
189
+ typeof content === "string" || content === undefined
190
+ ? content ? `${content}\n\n${text}` : text
191
+ : [...content, { type: "text", text }],
192
+ };
193
+ });
194
+
195
+ return () => controller.abort();
196
+ },
197
+ };
198
+
199
+ /** OpenCode 1 implementation (`@opencode-ai/plugin`, >= 1.18.29). */
200
+ const v1: PluginModule = {
201
+ id: ID,
202
+ async server({ client, directory, worktree }) {
203
+ const root = worktree || directory;
204
+
205
+ const hooks: Hooks = {
206
+ "tool.execute.after": async (input, output) => {
207
+ if (!FILE_TOOLS.has(input.tool)) return;
208
+
209
+ const filePaths = touchedFiles(input.args, output.metadata);
210
+ if (filePaths.size === 0) return;
211
+
212
+ const { reports, warnings } = await validate(root, filePaths);
213
+
214
+ for (const warning of warnings) {
215
+ await client.app.log({ body: { service: ID, level: "warn", message: warning } });
216
+ }
217
+
218
+ if (reports.length > 0) output.output += `\n\n${formatReports(reports)}`;
219
+ },
220
+ };
221
+
222
+ return hooks;
223
+ },
224
+ };
225
+
226
+ export default { ...v2, server: v1.server };
@@ -15,7 +15,7 @@ repos:
15
15
  - id: check-json
16
16
  - id: detect-private-key
17
17
  - id: mixed-line-ending
18
- args: ["--fix=lf"]
18
+ args: [--fix=lf]
19
19
  - id: no-commit-to-branch
20
20
  args: [--branch, main]
21
21
  - id: pretty-format-json
@@ -25,7 +25,7 @@ repos:
25
25
  # Documentation available at
26
26
  # https://gitlab.com/gitlab-com/gl-infra/common-ci-tasks/-/blob/main/docs/pre-commit.md
27
27
  - repo: https://gitlab.com/gitlab-com/gl-infra/common-ci-tasks
28
- rev: v5.24 # renovate:managed
28
+ rev: v5.46 # renovate:managed
29
29
 
30
30
  hooks:
31
31
  - id: shellcheck # Run shellcheck for changed Shell files
@@ -36,3 +36,4 @@ repos:
36
36
  - id: gitleaks # Detect hardcoded secrets using Gitleaks
37
37
  - id: editorconfig # Validate text files against .editorconfig
38
38
  - id: yamllint # Validate YAML files using yamllint
39
+ - id: ensure-claude-md
data/.rubocop_todo.yml CHANGED
@@ -151,12 +151,6 @@ Lint/SymbolConversion:
151
151
  - 'spec/labkit/logging/json_logger_spec.rb'
152
152
  - 'spec/support/tracing/shared_examples.rb'
153
153
 
154
- # Offense count: 1
155
- # Configuration parameters: Methods.
156
- Lint/UnexpectedBlockArity:
157
- Exclude:
158
- - 'tools/update-changelog.rb'
159
-
160
154
  # Offense count: 41
161
155
  # This cop supports safe autocorrection (--autocorrect).
162
156
  # Configuration parameters: AutoCorrect, AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods, NotImplementedExceptions.
@@ -196,13 +190,6 @@ Naming/RescuedExceptionsVariableName:
196
190
  Exclude:
197
191
  - 'lib/labkit/logging/grpc/server_interceptor.rb'
198
192
 
199
- # Offense count: 1
200
- # This cop supports safe autocorrection (--autocorrect).
201
- # Configuration parameters: EnabledForFlattenWithoutParams.
202
- Performance/FlatMap:
203
- Exclude:
204
- - 'tools/update-changelog.rb'
205
-
206
193
  # Offense count: 1
207
194
  Performance/MethodObjectAsBlock:
208
195
  Exclude:
@@ -402,7 +389,7 @@ Style/FileNull:
402
389
  - 'spec/labkit/middleware/sidekiq/user_experience_sli/server_spec.rb'
403
390
  - 'spec/spec_helper.rb'
404
391
 
405
- # Offense count: 8
392
+ # Offense count: 7
406
393
  # This cop supports unsafe autocorrection (--autocorrect-all).
407
394
  # Configuration parameters: EnforcedStyle.
408
395
  # SupportedStyles: always, always_true, never
@@ -415,7 +402,6 @@ Style/FrozenStringLiteralComment:
415
402
  - 'spec/labkit/tracing/rails/active_support/cache_read_instrumenter_spec.rb'
416
403
  - 'spec/labkit/tracing/rails/active_support/cache_write_instrumenter_spec.rb'
417
404
  - 'spec/support/grpc_service/test_services_pb.rb'
418
- - 'tools/update-changelog.rb'
419
405
 
420
406
  # Offense count: 2
421
407
  # This cop supports unsafe autocorrection (--autocorrect-all).
@@ -539,7 +525,7 @@ Style/StringConcatenation:
539
525
  - 'lib/labkit/tracing/jaeger_factory.rb'
540
526
  - 'lib/labkit/tracing/redis/redis_interceptor_helper.rb'
541
527
 
542
- # Offense count: 6
528
+ # Offense count: 4
543
529
  # This cop supports safe autocorrection (--autocorrect).
544
530
  # Configuration parameters: EnforcedStyle.
545
531
  # SupportedStyles: single_quotes, double_quotes
@@ -549,7 +535,6 @@ Style/StringLiteralsInInterpolation:
549
535
  - 'lib/labkit/tracing/grpc/server_interceptor.rb'
550
536
  - 'lib/labkit/tracing/jaeger_factory.rb'
551
537
  - 'spec/labkit/logging/json_logger_spec.rb'
552
- - 'tools/update-changelog.rb'
553
538
 
554
539
  # Offense count: 10
555
540
  # This cop supports safe autocorrection (--autocorrect).
data/AGENTS.md CHANGED
@@ -1,3 +1,4 @@
1
+ <<<<<<< before updating
1
2
  # AGENTS.md
2
3
 
3
4
  Instructions for AI agents and automated tooling working in this repository.
@@ -134,3 +135,39 @@ When a change does not fit one layer clearly, say so in the MR instead of pickin
134
135
  Mention the sync agent on the review thread to have it draft the scenario MR; if it cannot, open a labkit-spec issue and link it from the thread.
135
136
  - Never edit Lua scripts, key construction, header names, metric names, or log field names to fix a Ruby-only bug.
136
137
  If a fix seems to need that, it is a contract change.
138
+ =======
139
+ # Agent guidelines
140
+
141
+ This project uses [Conventional Commits](https://www.conventionalcommits.org/).
142
+ Commit messages drive automated [semantic releases](https://semantic-release.gitbook.io/)
143
+ (see `.releaserc.json`), so use `feat:`, `fix:`, etc. prefixes to ensure the
144
+ correct version bump and changelog entry.
145
+
146
+ ## AI-authored GitLab comments
147
+
148
+ Wrap the full body of any comment, note, or reply you post to GitLab (issues,
149
+ merge requests, epics — via `glab`/`glab api`) in `<:robot:>` / `</:robot:>`
150
+ tags (GitLab emoji shortcode, renders as 🤖), so readers can tell at a glance
151
+ that it's AI-generated:
152
+
153
+ ```
154
+ <:robot:>
155
+
156
+ ...full comment body...
157
+
158
+ </:robot:>
159
+ ```
160
+
161
+ This applies to newly posted comments. It does not apply to code, commit
162
+ messages, or MR/issue descriptions unless asked.
163
+
164
+ <!--
165
+ ####################################################################
166
+ # 🌊✨ PLEASE ADD PROJECT SPECIFIC RULES BELOW THIS LINE ✨🌊 #
167
+ # The section above is managed by the common-template-copier #
168
+ # template and is updated automatically on `copier update`. #
169
+ # Add your project-specific instructions below this line so #
170
+ # they are preserved when the template is updated. #
171
+ ####################################################################
172
+ -->
173
+ >>>>>>> after updating
data/CLAUDE.md ADDED
@@ -0,0 +1 @@
1
+ @AGENTS.md
data/CODEOWNERS CHANGED
@@ -1,4 +1,4 @@
1
1
  # CODEOWNERS is used to lookup assignees for
2
2
  # Renovate Bot dependency change Merge Requests.
3
3
  # https://docs.renovatebot.com/configuration-options/#assigneesfromcodeowners
4
- * @reprazent @ayufan @hmerscher @e_forbes @M_Alvarez @mwoolf @sankalp_gl @hardikgala @nindurkar @ashs2
4
+ * @ayufan @hmerscher @e_forbes @M_Alvarez @mwoolf @sankalp_gl @hardikgala @nindurkar @ashs2
data/CONTRIBUTING.md CHANGED
@@ -6,7 +6,7 @@ Except for the license granted herein to GitLab Inc. and recipients of software
6
6
  distributed by GitLab Inc., you reserve all right, title, and interest in and to
7
7
  your Contributions.
8
8
 
9
- All contributions are subject to the Developer Certificate of Origin and license set out at [docs.gitlab.com/ce/legal/developer_certificate_of_origin](https://docs.gitlab.com/ce/legal/developer_certificate_of_origin).
9
+ All contributions are subject to the Developer Certificate of Origin and license set out at [docs.gitlab.com/legal/developer_certificate_of_origin](https://docs.gitlab.com/legal/developer_certificate_of_origin/).
10
10
 
11
11
  _This notice should stay as the first item in the CONTRIBUTING.md file._
12
12
 
data/Gemfile CHANGED
@@ -3,3 +3,8 @@
3
3
  source "https://rubygems.org"
4
4
 
5
5
  gemspec
6
+
7
+ # Exports RSpec results to the DX Observer when GLCI_OBSERVER_AUTH_TOKEN is set.
8
+ # Exporter source: https://gitlab.com/gitlab-org/quality/analytics/test-metrics-exporters
9
+ # Owned by: @gitlab-org/quality/analytics (group::development analytics)
10
+ gem 'gitlab-rspec-metrics-exporter', '~> 0.2', groups: [:development, :test]
data/README.md CHANGED
@@ -80,27 +80,14 @@ pass.
80
80
 
81
81
  Please also review the [development section of the LabKit (go) README](https://gitlab.com/gitlab-org/labkit#developing-labkit) for details of the LabKit architectural philosophy.
82
82
 
83
- To work on some of the scripts we use for releasing a new version,
84
- make sure to add a new `.env.sh`.
85
-
86
- ```console
87
- cp .env.example.sh .env.sh`
88
- ```
89
-
90
- Inside `.env.sh`, add a personal acccess token for the `CHANGELOG_GITLAB_TOKEN`
91
- environment variable. Next source the file:
92
-
93
- ```console
94
- . .env.sh
95
- ```
96
-
97
83
  ### Releasing a new version
98
84
 
99
- Releasing a new version can be done by pushing a new tag, or creating
100
- it from the
101
- [interface](https://gitlab.com/gitlab-org/labkit-ruby/-/tags).
102
-
103
- A new changelog will automatically be added to the release on Gitlab.
85
+ Releases are cut automatically by
86
+ [semantic-release](https://github.com/semantic-release/semantic-release)
87
+ when changes are merged to `master` or to an `N-N-stable` branch. The
88
+ [Conventional Commits](https://www.conventionalcommits.org/) type of each
89
+ commit decides the version bump (see [AGENTS.md](AGENTS.md)), and the
90
+ release notes are generated from those commit messages.
104
91
 
105
92
  The new version will automatically be published to `gitlab-labkit` on
106
93
  [rubygems](https://rubygems.org/gems/gitlab-labkit) when the pipeline
data/lib/labkit/fields.rb CHANGED
@@ -16,6 +16,12 @@ module Labkit
16
16
  # GitLab username.
17
17
  GL_USER_NAME = "gl_user_name"
18
18
 
19
+ # Type of key used for authentication (e.g. "deploy_key", "key").
20
+ GL_KEY_TYPE = "gl_key_type"
21
+
22
+ # Numeric ID of the key used for authentication.
23
+ GL_KEY_ID = "gl_key_id"
24
+
19
25
  # Duo Workflow definition identifier (e.g. "analytics_agent/v1"). Identifies
20
26
  # which Duo Workflow agent originated a request, enabling per-agent
21
27
  # filtering in Kibana and Grafana.
@@ -149,12 +155,19 @@ module Labkit
149
155
  # connection field.
150
156
  GRAPHQL_CONNECTION_NODES = "graphql_connection_nodes"
151
157
 
158
+ # Protocol or subsystem that produced an access log line (e.g. "http",
159
+ # "grpc"). Emitted by the LabKit access-logging middleware so a single
160
+ # service's HTTP and gRPC access logs can be told apart.
161
+ SYSTEM = "system"
162
+
152
163
  # Maps each field constant to its logging field variant version.
153
164
  # A version of 0 means the field is not yet assigned to any variant.
154
165
  VARIANT_VERSION = {
155
166
  CORRELATION_ID => 1,
156
167
  GL_USER_ID => 1,
157
168
  GL_USER_NAME => 1,
169
+ GL_KEY_TYPE => 0,
170
+ GL_KEY_ID => 0,
158
171
  DUO_WORKFLOW_DEFINITION => 0,
159
172
  DUO_WORKFLOW_ID => 0,
160
173
  ERROR_TYPE => 0,
@@ -192,6 +205,7 @@ module Labkit
192
205
  ADDITIONAL_DETAILS => 0,
193
206
  GRAPHQL_COMPLEXITY_RAW => 0,
194
207
  GRAPHQL_CONNECTION_NODES => 0,
208
+ SYSTEM => 0,
195
209
  }.freeze
196
210
 
197
211
  # Get the constant name for a field value
@@ -66,7 +66,7 @@ Labkit::JsonSchema::RefResolver.cache.clear
66
66
 
67
67
  ## Use Case Example
68
68
 
69
- The `RefResolver` is used in the User Experience SLI Registry [lib/labkit/user_experience_sli/registry.rb](lib/labkit/user_experience_sli/registry.rb) to validate user experience definitions against a JSON schema.
69
+ The `RefResolver` is used in the User Experience SLI Registry [lib/labkit/user_experience_sli/registry.rb](../user_experience_sli/registry.rb) to validate user experience definitions against a JSON schema.
70
70
 
71
71
  ## Implementation Details
72
72
 
@@ -173,7 +173,7 @@ RSpec::Matchers.define :complete_user_experience do |user_experience_id, error:
173
173
  "Failed to complete user experience '#{user_experience_id}':\n" \
174
174
  "expected checkpoint='end' counter to increase by 1, but increased by #{@checkpoint_change}\n" \
175
175
  "expected total='error: #{error}' counter to increase by 1, but increased by #{@total_change}\n" \
176
- "expected apdex='success: #{success}' counter to increase by 1, but increased by #{@apdex_change}"
176
+ "expected apdex='success: #{success}' counter to increase by #{error ? 0 : 1}, but increased by #{@apdex_change}"
177
177
  end
178
178
 
179
179
  match_when_negated do |actual|
@@ -192,7 +192,7 @@ RSpec::Matchers.define :complete_user_experience do |user_experience_id, error:
192
192
  @total_change = total_after - total_before
193
193
  @apdex_change = apdex_after - apdex_before
194
194
 
195
- @checkpoint_change.zero? && @total_change.zero? && @apdex_change == (error ? 1 : 0)
195
+ @checkpoint_change.zero? && @total_change.zero? && @apdex_change.zero?
196
196
  end
197
197
 
198
198
  failure_message_when_negated do
data/performance.yml ADDED
@@ -0,0 +1,70 @@
1
+ # Performance contract for labkit-ruby
2
+ # https://handbook.gitlab.com/handbook/engineering/testing/performance-contracts/
3
+ #
4
+ # This file is the single entry point for performance contract tooling.
5
+ # Customize the sections relevant to your service and remove the rest.
6
+ # Schema reference: https://handbook.gitlab.com/handbook/engineering/testing/performance-contracts/#schema-definition
7
+
8
+ version: "1.0"
9
+ service:
10
+ name: "labkit-ruby"
11
+ description: "Performance contract for labkit-ruby"
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Frontend / UI contracts (SiteSpeed)
15
+ # Uncomment and configure if this service has a frontend component.
16
+ # Budget files live in the sitespeed-measurement-setup submodule.
17
+ # ---------------------------------------------------------------------------
18
+ # frontend:
19
+ # enabled: true
20
+ # budgets:
21
+ # production: testrunner/sitespeed-measurement-setup/performance/budgets/environments/production.json
22
+ # staging: testrunner/sitespeed-measurement-setup/performance/budgets/environments/staging.json
23
+ # mr: testrunner/sitespeed-measurement-setup/performance/budgets/environments/mr.json
24
+ # teams:
25
+ # labkit-ruby:
26
+ # url_dir: testrunner/sitespeed-measurement-setup/gitlab/desktop/urls
27
+ # budget: testrunner/sitespeed-measurement-setup/performance/budgets/teams/labkit-ruby.json
28
+ # default_budget: mr
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Backend / Service contracts (k6 / CPT)
32
+ # Define endpoint categories with latency and error-rate targets.
33
+ # Choose a tier as a starting point, then tune from baseline data.
34
+ #
35
+ # Tier 1 (fast reads): p95=100ms, p99=250ms, error_rate=0.001
36
+ # Tier 2 (std reads): p95=500ms, p99=1000ms, error_rate=0.005
37
+ # Tier 3 (writes): p95=1500ms, p99=3000ms, error_rate=0.01
38
+ # Tier 4 (git ops): p95=5000ms, p99=10000ms,error_rate=0.001
39
+ # ---------------------------------------------------------------------------
40
+ # endpoints:
41
+ # fast_reads:
42
+ # description: >
43
+ # Single item lookup by ID. Simulates one indexed DB read.
44
+ # routes:
45
+ # - "GET /api/v1/items/{id}"
46
+ # metrics:
47
+ # latency_p95_ms: 100
48
+ # latency_p99_ms: 250
49
+ # error_rate_threshold: 0.001
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Resource budgets (informational; enforcement planned for a future iteration)
53
+ # ---------------------------------------------------------------------------
54
+ # resources:
55
+ # memory_limit_mb: 256
56
+ # cpu_limit_cores: 0.5
57
+ # connection_pool_max: 10
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # SLI mapping -- links contract endpoints to Prometheus metrics emitted by
61
+ # LabKit v2. Fill in once your service is instrumented.
62
+ # ---------------------------------------------------------------------------
63
+ # sli_mapping:
64
+ # metrics_namespace: gitlab
65
+ # component: labkit-ruby
66
+ # fast_reads:
67
+ # requests_total_metric: gitlab_http_requests_total
68
+ # duration_metric: gitlab_http_request_duration_seconds
69
+ # endpoint_id_label: "GET /api/v1/items/{id}"
70
+ # feature_category_label: labkit_ruby
@@ -3,6 +3,7 @@
3
3
  # Consider contributing upstream when updating this file
4
4
 
5
5
  set -euo pipefail
6
+ IFS=$'\n\t'
6
7
 
7
8
  # ---------------------------------------------------------
8
9
  # This script will prepare your development environment
@@ -21,6 +22,28 @@ warn() {
21
22
  echo >&2 -e "Recommended reading: https://gitlab.com/gitlab-com/gl-infra/common-ci-tasks/-/blob/main/docs/developer-setup.md"
22
23
  }
23
24
 
25
+ # `mise plugins update` contacts GitHub for every registered plugin: slow, and
26
+ # it adds up when many vendored copies of this script run across many projects
27
+ # on the same machine. Throttle it to once a day using a stamp file in the
28
+ # user's cache directory, deliberately outside the project so that the throttle
29
+ # is shared by every project that vendors this script.
30
+ mise_plugins_update() {
31
+ local stamp_dir="${XDG_CACHE_HOME:-${HOME:-}/.cache}/common-template-copier"
32
+ local stamp_file="${stamp_dir}/mise-plugins-update"
33
+
34
+ # `find -mtime -1` rather than `stat`, which is spelled differently on
35
+ # GNU/BSD. It prints nothing when the stamp is missing or over a day old.
36
+ if [[ -z ${FORCE_MISE_PLUGINS_UPDATE-} ]] && [[ -n $(find "$stamp_file" -mtime -1 2>/dev/null) ]]; then
37
+ echo >&2 "skipping 'mise plugins update' (ran in the last 24h; set FORCE_MISE_PLUGINS_UPDATE=1 to force)"
38
+ return 0
39
+ fi
40
+
41
+ mise plugins update -q
42
+
43
+ # Best effort: a machine without a writable cache dir just updates every time.
44
+ mkdir -p "$stamp_dir" && touch "$stamp_file" || true
45
+ }
46
+
24
47
  if command -v mise >/dev/null; then
25
48
  echo >&2 -e "mise installed..."
26
49
  elif command -v rtx >/dev/null; then
@@ -53,8 +76,8 @@ fi
53
76
 
54
77
  # install mise/asdf dependencies
55
78
  echo "installing required plugins with mise install.."
56
- mise plugins update -q
57
79
  mise trust --yes
80
+ mise_plugins_update
58
81
  mise install
59
82
 
60
83
  # set PROMPT_COMMAND to empty value for mise if unset
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gitlab-labkit
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.6.0
4
+ version: 5.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrew Newdigate
@@ -562,9 +562,10 @@ executables:
562
562
  extensions: []
563
563
  extra_rdoc_files: []
564
564
  files:
565
+ - ".claude/hooks/precommit-validate.sh"
566
+ - ".claude/settings.json"
565
567
  - ".copier-answers.yml"
566
568
  - ".editorconfig"
567
- - ".env.example.sh"
568
569
  - ".gitignore"
569
570
  - ".gitlab-ci-asdf-versions.yml"
570
571
  - ".gitlab-ci-other-versions.yml"
@@ -574,6 +575,7 @@ files:
574
575
  - ".gitlab/merge_request_templates/default.md"
575
576
  - ".gitleaks.toml"
576
577
  - ".mise.toml"
578
+ - ".opencode/plugins/precommit-validate.ts"
577
579
  - ".pre-commit-config.yaml"
578
580
  - ".releaserc.json"
579
581
  - ".rspec"
@@ -583,6 +585,7 @@ files:
583
585
  - ".tool-versions"
584
586
  - ".yamllint.yaml"
585
587
  - AGENTS.md
588
+ - CLAUDE.md
586
589
  - CODEOWNERS
587
590
  - CONTRIBUTING.md
588
591
  - Dangerfile
@@ -712,6 +715,7 @@ files:
712
715
  - lib/labkit/user_experience_sli/experience.rb
713
716
  - lib/labkit/user_experience_sli/null.rb
714
717
  - lib/labkit/user_experience_sli/registry.rb
718
+ - performance.yml
715
719
  - renovate.json
716
720
  - scripts/prepare-dev-env.sh
717
721
  - scripts/update-asdf-version-variables.sh
data/.env.example.sh DELETED
@@ -1,7 +0,0 @@
1
- export CI_PROJECT_ID=10947578
2
- export CI_API_V4_URL="https://gitlab.com/api/v4"
3
- export CI_PROJECT_URL="https://gitlab.com/gitlab-org/ruby/gems/labkit-ruby"
4
- # Don't keep secrets in plaintext files. Use a keyring or 1password to load
5
- # it instead and export it as an env var.
6
- token=$(load-your-token)
7
- export GITLAB_TOKEN=$token