@harnessforce/cli 0.0.0-bootstrap.0 → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # @harnessforce/cli
2
+
3
+ `harnessforce`, the command line of [Harnessforce](https://github.com/lambda-script/harnessforce-agent). It
4
+ connects a machine to a Harnessforce Workspace, supplies the ingest key to Claude Code's OpenTelemetry
5
+ exporter, launches an agent linked to an Issue, and imports the metadata of past Claude Code sessions.
6
+
7
+ It is used together with the `harnessforce` Claude Code plugin, whose `/harnessforce:setup` installs
8
+ it. Public distribution on npm starts once the production domain of Harnessforce is decided; until
9
+ then, install it from the [local marketplace build](https://github.com/lambda-script/harnessforce-agent/blob/main/docs/runbooks/local-marketplace.md).
10
+
11
+ ## Requirements
12
+
13
+ - Node.js 18 or later (the same Node.js the plugin hook uses).
14
+ - An OS keychain: macOS Keychain, the Secret Service on Linux, or the Windows Credential Manager.
15
+ Keys and tokens are never written to a plain file.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm install -g @harnessforce/cli
21
+ harnessforce init
22
+ ```
23
+
24
+ ## Commands
25
+
26
+ | Command | What it does |
27
+ | --- | --- |
28
+ | `harnessforce init [--url <base URL>] [--port <port>] [--send-content]` | Logs in with the browser, stores a user ingest key and an API token in the keychain, and configures Claude Code and Codex |
29
+ | `harnessforce otel-headers` | Prints the `Authorization` header for Claude Code's `otelHeadersHelper` |
30
+ | `harnessforce run --issue <identifier> -- <agent> [args]` | Launches an agent with its session linked to an Issue |
31
+ | `harnessforce import` | Sends the metadata of past Claude Code sessions in connected repositories |
32
+ | `harnessforce tune [--all] [--no-send] [--show-report] [--json]` | Analyzes past sessions on this machine by public rules and sends the counts (analysis reports) |
33
+ | `harnessforce tune record` / `harnessforce tune --purge` | Records a proposal from stdin / deletes everything under `~/.harnessforce/tune/` |
34
+ | `harnessforce top [--once] [--json] [--ascii] [--theme <auto\|light\|dark\|ansi>]` | Shows the Claude Code and Codex sessions on this machine in the terminal: state, tokens, context and tool failures. Reads only local files and never connects to Harnessforce |
35
+ | `harnessforce hook session-start` | The entry of Codex's `SessionStart` hook: reads `session_id`, `cwd` and `source` from stdin, registers the session, and prints the session ID for the agent's context. Always exits 0 |
36
+ | `harnessforce usage-limits on [--yes]` / `off` / `status` | Shares your usage limits with the workspace after you agree to the consent text (`on`), or withdraws the consent, deletes the stored values and restores your previous statusLine (`off`), or shows the consent, the workspace opt-in and whether the statusLine is wrapped (`status`). Not supported on Windows |
37
+ | `harnessforce usage-limits statusline` | A statusLine command that wraps your existing one: it passes stdin to the original command, returns its output and exit code unchanged, then sends only the usage percentage and reset time of the 5-hour and 7-day windows. It sends nothing until you have consented |
38
+ | `harnessforce --version` | Prints the version |
39
+
40
+ ## Watching your sessions (`harnessforce top`)
41
+
42
+ `harnessforce top` reads the Claude Code transcripts on this machine (the same place as `harnessforce import`) and the
43
+ Codex rollouts (`sessions/YYYY/MM/DD/rollout-*.jsonl` under `$CODEX_HOME` when it is an absolute path, otherwise
44
+ `~/.codex`) and shows one row per session whose last event is within 24 hours. It needs no `harnessforce init`, makes no network
45
+ connection, never reads the keychain and writes nothing to disk. It shows counts, times, ids, the repository and
46
+ branch, model and tool names only: no prompt, response, tool input or output, path, command or error text, no cost and
47
+ no context percentage.
48
+
49
+ - The `agent` column says `claude` or `codex`; `--json` uses `claude_code` or `codex`. For Codex, the tool failure
50
+ count is blank (`tool_failures` is `null`) because Codex does not save whether a call succeeded; the tool column
51
+ shows the call count only. Rollouts compressed to `.jsonl.zst` (Codex does this after 7 days) and
52
+ `archived_sessions` are not read.
53
+ - A session is `active` when its last event is within 60 seconds, otherwise `idle`.
54
+ - Keys: `q` quit, `?` help, `↑` `↓` / `j` `k` select, `Enter` detail, `Esc` back, `/` filter, `s` order, `p` pause, `r` refresh.
55
+ - `--once` prints one plain-text table (no escapes). `--json` prints `{"sessions": [...]}`. A pipe or redirect behaves like `--once`.
56
+ - `--ascii` draws with ASCII characters only.
57
+ - The terminal background is never painted. Colors are foreground only, so a symbol and its label always carry the
58
+ meaning. `--theme auto` asks the terminal for its background once (100 ms limit); when it answers, the colors of the
59
+ Harnessforce web design system are used, and any color with less than 3:1 contrast on that background is left out.
60
+ Without an answer, or with `--theme ansi`, the terminal's own 16 colors are used. `NO_COLOR` turns colors off.
61
+ - The screen restores the alternate screen and the cursor on `q`, Ctrl-C, SIGTERM, SIGHUP and a normal exit. A console that does not understand VT escape sequences is not detected: use `--once` or `--ascii` there.
62
+ - `~/.harnessforce/config.json` may set `{"top": {"ambiguous_width": 2, "braille": true}}`. An unreadable file or a
63
+ value out of range falls back to the defaults and says so; the file is never written.
64
+
65
+ ## Codex `SessionStart` hook (`harnessforce hook session-start`)
66
+
67
+ Codex runs this command through the `[[hooks.SessionStart]]` entry that `harnessforce init` writes into Codex's
68
+ `config.toml`. It uses only `session_id`, `cwd` and `source` from the JSON on stdin, and:
69
+
70
+ - sends the session registration (`agent` is `codex`) only when `source` is `startup`, `clear` or missing, and
71
+ only to the ingest origin that `harnessforce init` pinned, with the user ingest key from the keychain. The
72
+ Workspace and the endpoint come from `HARNESSFORCE_WORKSPACE_ID` and `HARNESSFORCE_ENDPOINT`, or from the
73
+ Claude Code user settings that `harnessforce init` wrote. When `HARNESSFORCE_ISSUE` is a valid identifier
74
+ (`harnessforce run --issue` sets it), the registration claims `source=cli` with that Issue.
75
+ - prints `{"hookSpecificOutput": {...}}` carrying `harnessforce session_id: <id>` so the agent knows its session
76
+ ID. When the key was revoked (401) it prints that line and the message as plain text instead, and writes the
77
+ message to stderr.
78
+ - never fails the session: any error ends with exit code 0, and nothing is sent outside a git repository.
79
+
80
+ ## Usage limits in the statusLine (`harnessforce usage-limits statusline`)
81
+
82
+ Claude Code passes the plan limits (`rate_limits`) only to the statusLine command, not to hooks. `harnessforce usage-limits statusline` is meant to sit in front of the statusLine you already use (for example claude-hud):
83
+
84
+ - It reads all of stdin and, if `~/.harnessforce/usage-limits.json` has an `original` command, runs it with `sh -c`, hands it the same stdin and the same environment, and returns its stdout, stderr and exit code as they are. No time limit is added.
85
+ - After that, only if `usage-limits.json` records your consent for the current text version, it takes `rate_limits.five_hour` and `rate_limits.seven_day` (`used_percentage` and `resets_at`) and sends them to `POST <ingest endpoint>/v1/usage-limits` with the user ingest key from the keychain. Nothing else in the JSON (`cwd`, `transcript_path`, `cost`, and so on) is read or sent.
86
+ - The send runs in a detached child process with stdin, stdout and stderr closed, so the statusLine is never delayed. A failure does not change the output or the exit code.
87
+ - It sends at most once every 5 minutes, unless the reset time of a window changed. The time and the reset times of the last send are kept in `~/.harnessforce/usage-limits-state.json` (owner-only).
88
+
89
+ ### Turning it on and off
90
+
91
+ `harnessforce usage-limits on` shows the consent text, asks `y` (skipped with `--yes`), records the consent (`PUT /api/v1/cli/usage-limits/consent`), and then wraps the `statusLine` in your Claude Code user settings: only `command` is replaced with `harnessforce usage-limits statusline`, so `type`, `padding`, `refreshInterval` and the other keys stay. The statusLine you had (for example claude-hud) is saved as-is in `~/.harnessforce/usage-limits.json`. If the statusLine is not `type: "command"`, or the settings cannot be read, nothing is recorded or changed. If writing the mark or the settings fails, the consent is withdrawn again. `harnessforce usage-limits off` withdraws the consent first and then puts the saved statusLine back (or removes it if there was none); a statusLine that another tool has changed since is left alone.
92
+
93
+ ## What is never sent
94
+
95
+ Harnessforce never turns on prompt or body logging by itself. `harnessforce run` never turns it on, and `harnessforce init`
96
+ adds `OTEL_LOG_USER_PROMPTS=1` to the Claude Code user settings only with `--send-content`, and only
97
+ when the credentials response says the Workspace has opted in to content. Without that, prompts,
98
+ responses, tool inputs and outputs, and file contents are not sent. For a Workspace that has not opted
99
+ in, `harnessforce init --send-content` leaves the setting alone, prints the reason, and still exits 0. `harnessforce run`
100
+ never puts the user key or the API token in the agent's environment, arguments or settings. Keys and
101
+ tokens are sent only to the origins pinned by `harnessforce init`.
102
+
103
+ ## CLI credentials (`harnessforce init`, `harnessforce otel-headers`)
104
+
105
+ `harnessforce init [--url <base URL>] [--port <port>] [--send-content]` connects this machine to a Harnessforce Workspace:
106
+
107
+ 1. It checks the OS keychain first: macOS Keychain, the Secret Service on Linux, or the Windows
108
+ Credential Manager (through [`@napi-rs/keyring`](https://github.com/Brooooooklyn/keyring-node)).
109
+ Without one it stops. Keys are never written to a plain file.
110
+ 2. It logs in with the browser: OAuth 2.0 authorization code with PKCE, a `127.0.0.1:8080` loopback
111
+ redirect (`--port <port>` changes the port), the endpoint discovered from
112
+ `/.well-known/oauth-authorization-server`, and a 5 minute wait. When the port is already in use it
113
+ stops instead of moving to another port. If the browser cannot be opened, it prints the URL.
114
+ 3. It asks `POST <base URL>/api/v1/cli/credentials` for a user ingest key and an API token (a 1 hour
115
+ access token and a 90 day refresh token). It also sends the SHA-256 hashes of the ingest keys and of
116
+ the API tokens' refresh tokens already in the keychain (at most 100 of each), so the old key and
117
+ token for the chosen Workspace on this machine are revoked. Keys and tokens on other machines stay
118
+ valid.
119
+ 4. It stores both under the keychain service `harnessforce` as `<workspace_id>:ingest-key` and
120
+ `<workspace_id>:api-token` (a JSON object with the access token, the refresh token and their
121
+ expiries), and pins the ingest endpoint origin as `<workspace_id>:ingest-origin`
122
+ and the base URL origin as `<workspace_id>:url-origin`. It deletes both origins first and writes
123
+ them last, so a failure part way never pairs an old origin with a new key or token.
124
+ 5. It updates the Claude Code user settings (`~/.claude/settings.json`, or `$CLAUDE_CONFIG_DIR`),
125
+ changing only these keys:
126
+ - `env`: the OTel exporter variables, `HARNESSFORCE_URL`, `HARNESSFORCE_ENDPOINT` and
127
+ `HARNESSFORCE_WORKSPACE_ID`, but no key. With `--send-content` and a Workspace that has opted in
128
+ to content it also adds `OTEL_LOG_USER_PROMPTS=1`
129
+ - `otelHeadersHelper`: `harnessforce otel-headers`
130
+ - `enabledPlugins["harnessforce@harnessforce-agent"]`
131
+ 6. It updates the Codex `config.toml` (`$CODEX_HOME` when it is an absolute path, otherwise `~/.codex`),
132
+ changing only these three items and keeping every other key and comment:
133
+ - `[otel].exporter`: OTLP/HTTP (`protocol = "binary"`) to the ingest endpoint with
134
+ `Authorization = "Bearer <user ingest key>"`. Codex cannot take the header from a command or expand
135
+ `${VAR}`, so this is the one place a key is written to a plain file. It is the user ingest key only
136
+ (never the API token), and you can revoke it on the Workspace's send keys page. With `--send-content`
137
+ and a Workspace that has opted in to content it also sets `log_user_prompt = true`
138
+ - `[[hooks.SessionStart]]`: a handler that runs `harnessforce hook session-start`
139
+ - `[mcp_servers.harnessforce]`: `url = "<base URL>/mcp"`
140
+
141
+ The file is written through a temporary file in the same directory and renamed into place, with mode
142
+ `0600`. Running `harnessforce init` again replaces only these three items. Restart Codex afterwards,
143
+ trust the hook with `/hooks` (Codex runs an untrusted hook only after you review it), and run
144
+ `codex mcp login harnessforce` to use the MCP server.
145
+
146
+ `harnessforce otel-headers` prints `{"Authorization":"Bearer <key>"}`. The key is `HARNESSFORCE_INGEST_KEY` from
147
+ the managed settings file when that is set, and otherwise the user key for
148
+ `HARNESSFORCE_WORKSPACE_ID` from the keychain. If
149
+ there is no key, it prints nothing and exits 1. The user key is printed only when every destination
150
+ variable that is set (`HARNESSFORCE_ENDPOINT`, `OTEL_EXPORTER_OTLP_ENDPOINT` and the per-signal
151
+ `OTEL_EXPORTER_OTLP_*_ENDPOINT`) has the pinned origin. This stops a repository's
152
+ `.claude/settings.json` `env` from pointing the hook at another host to collect the key. Otherwise it
153
+ writes `harnessforce: user key withheld (destination not verified)` to stderr and exits 1. Run
154
+ `harnessforce init` again to re-pin.
155
+
156
+ ### Refreshing the API token
157
+
158
+ `harnessforce import` and `harnessforce run --issue` call the Read API with the access token. When it has expired, or the
159
+ Read API answers 401 once, they take `~/.harnessforce/token.lock`, read the keychain again (another
160
+ process may have refreshed already), and exchange the refresh token at the `token_endpoint` from the
161
+ authorization server metadata of the base URL, only when that endpoint is on the pinned base URL
162
+ origin. The new pair replaces `<workspace_id>:api-token`. A lock older than 60 seconds is treated as
163
+ abandoned, and waiting more than 30 seconds for it counts as a failed refresh. If the refresh fails, or
164
+ the refreshed token is also answered with 401, they stop with
165
+ 「ログインの有効期限が切れました。`harnessforce init`を実行してください」.
166
+
167
+ ### Default connection
168
+
169
+ The default base URL is an optional build input: `HARNESSFORCE_BUILD_URL=<apps/web base URL> pnpm build`.
170
+ Without it the default is `https://harnessforce.dev`. The value must be `https:`, or `http:` for localhost.
171
+ At run time the base URL is the environment variable `HARNESSFORCE_URL`, then `env.HARNESSFORCE_URL` in the
172
+ user settings (`harnessforce init --url` writes it), then the build default. The plugin build
173
+ uses the same value for its MCP server URL. See
174
+ [Building the local marketplace](https://github.com/lambda-script/harnessforce-agent/blob/main/docs/runbooks/local-marketplace.md).
175
+
176
+ ## Launching an agent for an Issue (`harnessforce run`)
177
+
178
+ `harnessforce run --issue <identifier> -- <agent> [args]` links the session to an Issue before it starts:
179
+
180
+ 1. It reads the Read API base URL (`HARNESSFORCE_URL`, then `env.HARNESSFORCE_URL` in the Claude Code user
181
+ settings, then the build default), the ingest endpoint (`HARNESSFORCE_ENDPOINT`, then the user
182
+ settings) and the Workspace (`HARNESSFORCE_WORKSPACE_ID`, then the user settings). Before sending
183
+ anything it checks, in order: the keychain, the Workspace, its user key, the ingest endpoint and its
184
+ scheme, the ingest origin pinned by `harnessforce init`, the API token, the Read API scheme, and the Read API
185
+ origin pinned by `harnessforce init`. The first failed check stops it, usually asking you to run `harnessforce init`.
186
+ 2. It resolves the Issue with `GET /api/v1/issues/{identifier}` and the stored API token. If the Issue
187
+ does not exist, it prints up to 10 candidates from `GET /api/v1/issues?query=<identifier>` and stops.
188
+ 3. It computes the config snapshot ID locally with the same collection as the SessionStart hook.
189
+ 4. It starts the agent with `HARNESSFORCE_WORKSPACE_ID`, `HARNESSFORCE_ENDPOINT`,
190
+ `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, telemetry and traces
191
+ enabled, `HARNESSFORCE_ISSUE`, and `OTEL_RESOURCE_ATTRIBUTES` carrying `hf.issue.identifier`,
192
+ `hf.vcs.repository`, `hf.vcs.branch`, `hf.vcs.commit` and `hf.agent.config_version`. It removes
193
+ `OTEL_EXPORTER_OTLP_HEADERS` and the per-signal `*_HEADERS`, `*_ENDPOINT` and `*_PROTOCOL` variables
194
+ inherited from the shell. The user key and the API token are never put in the agent's environment,
195
+ arguments or settings: Claude Code gets the key only through `otelHeadersHelper` (`harnessforce otel-headers`).
196
+ 5. For Claude Code (`claude`), the same values also go in a settings file passed as
197
+ `--settings <absolute path>` before your arguments, because settings files can override the shell.
198
+ The file is created with mode 0600 in the temp directory and deleted when the agent exits.
199
+ `HARNESSFORCE_ISSUE` tells the plugin hook to register the session with `source=cli`.
200
+ For Codex (`codex`, `codex.exe`, `codex.cmd`), only `HARNESSFORCE_WORKSPACE_ID`, `HARNESSFORCE_ENDPOINT` and
201
+ `HARNESSFORCE_ISSUE` are set, and no settings file is passed. Codex does not read `CLAUDE_CODE_*` or
202
+ `OTEL_RESOURCE_ATTRIBUTES`, and an `OTEL_EXPORTER_OTLP_ENDPOINT` would replace the endpoint of the `[otel]`
203
+ exporter that `harnessforce init` writes into Codex's `config.toml`, so the request could go out without its
204
+ header. The Issue is linked by the Codex `SessionStart` hook, which reads `HARNESSFORCE_ISSUE`. The variables
205
+ of your own shell are left as they are for Codex.
206
+ 6. The agent is found on `PATH` (with `PATHEXT` on Windows), or used as given when the command contains a
207
+ path separator. On Windows, `.cmd` and `.bat` files (such as npm's `claude.cmd`) are started through
208
+ `%ComSpec% /d /s /c` with every argument quoted; arguments containing `"`, `%`, `!` or a newline are
209
+ refused.
210
+
211
+ It exits with the agent's exit code. Prompt and body logging are never turned on.
212
+
213
+ ## Importing past sessions (`harnessforce import`)
214
+
215
+ `harnessforce import` sends metadata of past Claude Code sessions on this machine to Harnessforce, so that
216
+ work done before the plugin was installed can be linked to issues too. Run `harnessforce init` first.
217
+
218
+ - It reads the transcripts in `~/.claude/projects/<project>/<session>.jsonl` (or
219
+ `$CLAUDE_CONFIG_DIR/projects`). Their format is not documented, so the parser is versioned
220
+ (`parser_version`), and unreadable lines and files are skipped and counted.
221
+ - Only these values are sent: session ID, first prompt ID, start and end time, repository, branch,
222
+ the most used model, input and output token counts (without cache tokens), and the number of calls
223
+ and failures per tool. Prompts, responses and tool inputs and outputs are never sent.
224
+ - Only sessions whose `cwd` is in a repository connected to the Workspace are sent. The connected
225
+ repositories come from `GET <HARNESSFORCE_URL>/api/v1/repositories` (all pages) and the import
226
+ window from `session_import_days` (`GET <HARNESSFORCE_URL>/api/v1/workspace`), both with the API
227
+ token. The API token is sent only when the origin of `HARNESSFORCE_URL` matches the one pinned by
228
+ `harnessforce init`; otherwise nothing is sent and it asks you to run `harnessforce init`.
229
+ - Sessions are sent 100 at a time to `POST <HARNESSFORCE_ENDPOINT>/v1/imports/sessions` with the user
230
+ ingest key, only when the endpoint origin matches the one pinned by `harnessforce init`. `429` and `503` are
231
+ retried up to 3 times after `Retry-After` (at most 60 seconds).
232
+ - Sent sessions are recorded in `~/.harnessforce/import-state.json` per Workspace and ingest endpoint,
233
+ so running it again continues where it stopped and never sends a session twice to the same place.
234
+ Sessions dropped because of the monthly event limit or a read-only Workspace are not recorded and
235
+ are sent by a later run.
236
+
237
+ The Workspace, the connection URL and the ingest endpoint come from `HARNESSFORCE_WORKSPACE_ID`,
238
+ `HARNESSFORCE_URL` and `HARNESSFORCE_ENDPOINT` in the environment, and otherwise from the `env` that
239
+ `harnessforce init` wrote to the Claude Code user settings.
240
+
241
+ ## Analyzing past sessions (`harnessforce tune`)
242
+
243
+ `harnessforce tune` reads the same transcripts as `harnessforce import` and turns each session into an analysis report:
244
+ interventions, loops that could be automated, and MCP server calls. Run `harnessforce init` first. The Viewer
245
+ role cannot use it.
246
+
247
+ - The categories come from public rules and a public vocabulary (`src/tune/analyze.ts`,
248
+ `src/tune/vocabulary.ts`, `analyzer_version`), never from a model. Categories the transcript cannot
249
+ tell apart (`approval`, `answer`) are reported as not measured, never as 0.
250
+ - Only the counts and medians of the analysis report are sent, to
251
+ `POST <HARNESSFORCE_ENDPOINT>/v1/analysis-reports` with the user ingest key. Prompts, responses,
252
+ commands, paths and error text never leave the machine.
253
+ - By default it analyzes sessions started in the last 30 days in connected repositories. `--all`
254
+ analyzes every session, but still sends only sessions in connected repositories that started within
255
+ `session_import_days`. Sessions without a Run are imported first, like `harnessforce import`.
256
+ - Sending is fail-open: when Harnessforce cannot be reached, the reports stay in
257
+ `~/.harnessforce/tune/unsent.json` and are sent by the next run. `401` and `403` delete the unsent
258
+ reports and ask you to run `harnessforce init`.
259
+ - `--no-send`, or `{"tune": {"send_report": false}}` in `~/.harnessforce/config.json`, sends nothing.
260
+ A config file it cannot read also sends nothing.
261
+ - It also counts usage per session (auto and manual context compactions, responses, cache reuse
262
+ ratio, output tokens per model in the main and subagent transcripts). These values are shown and
263
+ written to `--json` and `~/.harnessforce/tune/analysis.json` only; they are never sent.
264
+ - `--json` also lists, for each recorded proposal whose application was detected, the value of its
265
+ category in the 14 days before and after the detection time (`followups`). The difference is not
266
+ a cause. Once a `--json` run outputs a follow-up whose after period has ended, later runs omit it.
267
+ - Everything it keeps is under `~/.harnessforce/tune/`; `harnessforce tune --purge` deletes it.
268
+
269
+ ## License
270
+
271
+ [Apache-2.0](https://github.com/lambda-script/harnessforce-agent/blob/main/LICENSE)