@yagni-app/code-staging 1.2.14-staging.2281.1 → 1.2.14-staging.2283.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -112,6 +112,19 @@ export declare const SANDBOX_SECTION: string;
112
112
  * contain the standalone word "pi", no `- ` bullet lines, no emojis.
113
113
  */
114
114
  export declare const SANDBOX_CLOUD_SECTION: string;
115
+ export declare const PLACED_VALUES_SECTION_HEADER = "## The System's values";
116
+ /**
117
+ * What a session on a machine that holds a yak's System values is told
118
+ * (YAG-1209): never read them. Appended only where the extension found the
119
+ * file at activation (`placedValues.ts`), so no other session's prompt
120
+ * changes. The paths are the backend's (`repos/system/needs/placement.ts`),
121
+ * created at run time, never on the image, so the image smoke does not read
122
+ * this section.
123
+ *
124
+ * Content constraints (parity with {@link SANDBOX_SECTION}): must not contain
125
+ * the standalone word "pi", no `- ` bullet lines, no emojis.
126
+ */
127
+ export declare const PLACED_VALUES_SECTION: string;
115
128
  /**
116
129
  * File-tool steering: prefer the first-class write/edit tools over bash file
117
130
  * writes, one write call per file instead of a heredoc batch, and never create
@@ -221,6 +234,11 @@ export interface BrandSystemPromptOptions {
221
234
  * {@link SANDBOX_CLOUD_SECTION} instead of {@link SANDBOX_SECTION}.
222
235
  */
223
236
  cloud?: boolean;
237
+ /**
238
+ * The machine holds a yak's System values (`placedValues.ts` found the
239
+ * file): {@link PLACED_VALUES_SECTION} is appended. Absent, nothing changes.
240
+ */
241
+ placedValues?: boolean;
224
242
  }
225
243
  /**
226
244
  * Rebrand pi's assembled system prompt as YAGNI Code's, and optionally inject a
@@ -253,6 +253,31 @@ export const SANDBOX_CLOUD_SECTION = `${SANDBOX_SECTION_HEADER}\n` +
253
253
  "and read one with " +
254
254
  "`gh api -H 'Accept: application/vnd.github.raw' 'repos/<owner>/<repo>/contents/<path>'`. " +
255
255
  "Nothing there is part of your change.";
256
+ export const PLACED_VALUES_SECTION_HEADER = "## The System's values";
257
+ /**
258
+ * What a session on a machine that holds a yak's System values is told
259
+ * (YAG-1209): never read them. Appended only where the extension found the
260
+ * file at activation (`placedValues.ts`), so no other session's prompt
261
+ * changes. The paths are the backend's (`repos/system/needs/placement.ts`),
262
+ * created at run time, never on the image, so the image smoke does not read
263
+ * this section.
264
+ *
265
+ * Content constraints (parity with {@link SANDBOX_SECTION}): must not contain
266
+ * the standalone word "pi", no `- ` bullet lines, no emojis.
267
+ */
268
+ export const PLACED_VALUES_SECTION = `${PLACED_VALUES_SECTION_HEADER}\n` +
269
+ "\n" +
270
+ "This machine holds the System's provided values, the credentials and test data its " +
271
+ "services run with, in `/run/yagni/secret/env` (linked at `/run/yagni/env`). Never read, " +
272
+ "print, copy or search that file, and never read a running service's environment " +
273
+ "(`/proc/<pid>/environ`, `docker inspect`, `env` or `printenv` run inside a container). " +
274
+ "A command that needs the values sources the file itself " +
275
+ "(`set -a; . /run/yagni/env; set +a; <command>`) and never prints one. Code you write " +
276
+ "reads a credential by its variable name, never as a literal, and no credential goes " +
277
+ "into a file, a commit message or your report. A credential that reaches you in any " +
278
+ "output shows as [REDACTED], and YAGNI does not push a change, commit message or pull " +
279
+ "request that holds one. Test data (a test user, seed records, the app's URL) and a " +
280
+ "public value show as they are, and a test may hold them.";
256
281
  /**
257
282
  * File-tool steering: prefer the first-class write/edit tools over bash file
258
283
  * writes, one write call per file instead of a heredoc batch, and never create
@@ -475,6 +500,11 @@ export function brandSystemPrompt(original, opts = {}) {
475
500
  else if (!s.includes(TICKET_IMAGE_RULE_HEADER)) {
476
501
  s = `${s}\n\n${TICKET_IMAGE_RULE_HEADER}\n${TICKET_IMAGE_RULE}`;
477
502
  }
503
+ // 5b1. YAG-1209: a machine that holds a yak's System values says never to
504
+ // read them, beside what the sandbox has. Same idempotency shape.
505
+ if (opts.placedValues && !s.includes(PLACED_VALUES_SECTION_HEADER)) {
506
+ s = `${s}\n\n${PLACED_VALUES_SECTION}`;
507
+ }
478
508
  // 5b2. GitHub operations — a standing directive added alongside
479
509
  // the ticket-image rule (same placement, same idempotency shape). It is
480
510
  // universal knowledge, not user policy, so it rides the branded prompt
@@ -27,6 +27,8 @@ import { maybeOfferMiningBeat as defaultMaybeOfferMiningBeat, type MineBeatMarke
27
27
  export interface RegisterYagniDeps {
28
28
  baseUrl?: string;
29
29
  getToken?: () => string | undefined;
30
+ /** Where a yak's System places its values (`placedValues.ts`); the backend's paths by default. */
31
+ placedValuePaths?: readonly string[];
30
32
  /** The token's ISO expiry, forwarded by the launcher (for the expiry notice). */
31
33
  getTokenExpiresAt?: () => string | undefined;
32
34
  /** Clock seam for the expiry notice (defaults to Date.now). */
@@ -63,6 +63,7 @@ import { registerDecisionCommands } from "./decisions.js";
63
63
  import { makeDecisionCapture } from "./decisionCapture.js";
64
64
  import { loadGroundingEnabled } from "./grounding.js";
65
65
  import { attributionPromptSection, loadAttributionSettings, } from "./attribution.js";
66
+ import { openPlacedValues, registerPlacedValueRedaction } from "./placedValues.js";
66
67
  import { registerAmbientRecall } from "./recall.js";
67
68
  import { resilientFetch } from "./resilientFetch.js";
68
69
  import { installNonZeroExitReporter, installUncaughtExceptionMonitor, makeCrashReporter, runningUnderTest, } from "./crashReport.js";
@@ -175,6 +176,10 @@ export async function registerYagni(pi, deps = {}) {
175
176
  // mode under the harness, where team_read is registered). A local eval
176
177
  // compare sets eval mode without the harness, so it keeps the laptop's.
177
178
  const sandboxSession = cloudSession || (evalMode && runsInSandboxHarness(env));
179
+ // YAG-1209: a yak's machine holds its System's values in a file this
180
+ // session could read. Opened only where the file is (null everywhere else,
181
+ // where nothing below changes); its handlers register last, at the end.
182
+ const placedValues = openPlacedValues(deps.placedValuePaths);
178
183
  // A timed /go stage child refuses every tool once its time is up. Order does
179
184
  // not matter: pi runs every tool_call handler until one blocks, and an allow
180
185
  // (a result without `block`) never ends the loop, so this block always lands.
@@ -1757,6 +1762,7 @@ export async function registerYagni(pi, deps = {}) {
1757
1762
  fileToolSteering: condensedToolsRegistered,
1758
1763
  ...(sandboxSession ? { sandbox: true } : {}),
1759
1764
  ...(cloudSession ? { cloud: true } : {}),
1765
+ ...(placedValues ? { placedValues: true } : {}),
1760
1766
  }),
1761
1767
  });
1762
1768
  // Turn-lifecycle WAL: a `turn_start` with no matching `turn_end` is the
@@ -2214,6 +2220,10 @@ export async function registerYagni(pi, deps = {}) {
2214
2220
  fields: { toolName: event.toolName, errorClass },
2215
2221
  });
2216
2222
  });
2223
+ // YAG-1209: last, so the placed values are replaced in whatever every
2224
+ // other tool_result and context handler above added.
2225
+ if (placedValues)
2226
+ registerPlacedValueRedaction(pi, placedValues);
2217
2227
  }
2218
2228
  export default async function (pi) {
2219
2229
  await registerYagni(pi);
@@ -37,10 +37,6 @@ export interface AddedText {
37
37
  export declare function scanAddedText(files: readonly AddedText[], sessionSecrets?: readonly string[]): Finding[];
38
38
  /** A binary file this run added or changed, other than an image: the host never stores one. */
39
39
  export declare function binaryFindings(paths: readonly string[]): Finding[];
40
- /**
41
- * A unified diff (`-U0`) as the text each file gained: its `+` lines with
42
- * their new line numbers. Deleted files and binary sections gain nothing.
43
- */
44
40
  export declare function addedTextOfDiff(diff: string): AddedText[];
45
41
  /** The git seam: argv run in `cwd`, resolving its exit code and output. */
46
42
  export type ScanExec = (argv: string[], cwd: string, signal?: AbortSignal) => Promise<{
@@ -218,17 +218,63 @@ export function binaryFindings(paths) {
218
218
  * A unified diff (`-U0`) as the text each file gained: its `+` lines with
219
219
  * their new line numbers. Deleted files and binary sections gain nothing.
220
220
  */
221
+ const C_ESCAPES = {
222
+ a: 7,
223
+ b: 8,
224
+ t: 9,
225
+ n: 10,
226
+ v: 11,
227
+ f: 12,
228
+ r: 13,
229
+ '"': 34,
230
+ "\\": 92,
231
+ };
232
+ /**
233
+ * A patch header's path as the file is named: git C-quotes a name holding a
234
+ * quote, a backslash, a tab or a newline (`"b/a\"b.txt"`) even with
235
+ * `core.quotepath=off`, and may append a tab after an unquoted one.
236
+ */
237
+ function gitHeaderPath(raw) {
238
+ if (!raw.startsWith('"'))
239
+ return raw.replace(/\t.*$/, "");
240
+ const end = raw.lastIndexOf('"');
241
+ // By code point, so a character outside the BMP (an emoji) stays whole.
242
+ const inner = Array.from(raw.slice(1, end > 0 ? end : undefined));
243
+ const bytes = [];
244
+ for (let at = 0; at < inner.length; at++) {
245
+ const char = inner[at];
246
+ if (char !== "\\") {
247
+ bytes.push(...Buffer.from(char, "utf8"));
248
+ continue;
249
+ }
250
+ const octal = /^[0-7]{3}$/.exec(inner.slice(at + 1, at + 4).join(""));
251
+ if (octal) {
252
+ bytes.push(Number.parseInt(octal[0], 8));
253
+ at += 3;
254
+ }
255
+ else {
256
+ const next = inner[at + 1] ?? "";
257
+ bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0));
258
+ at += 1;
259
+ }
260
+ }
261
+ return Buffer.from(bytes).toString("utf8");
262
+ }
221
263
  export function addedTextOfDiff(diff) {
222
264
  const files = [];
223
265
  let current;
224
266
  let next = 0;
267
+ // A file's header comes before its first hunk: inside one, a line that
268
+ // reads `+++ ` is an added line that starts `++ `, never a header.
269
+ let inHunk = false;
225
270
  for (const raw of diff.split("\n")) {
226
271
  if (raw.startsWith("diff --git ")) {
227
272
  current = undefined;
273
+ inHunk = false;
228
274
  continue;
229
275
  }
230
- if (raw.startsWith("+++ ")) {
231
- const path = raw.slice(4).replace(/\t.*$/, "");
276
+ if (!inHunk && raw.startsWith("+++ ")) {
277
+ const path = gitHeaderPath(raw.slice(4));
232
278
  current = path === "/dev/null" ? undefined : { path: path.replace(/^b\//, ""), lines: [] };
233
279
  if (current)
234
280
  files.push(current);
@@ -237,9 +283,10 @@ export function addedTextOfDiff(diff) {
237
283
  const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
238
284
  if (hunk) {
239
285
  next = Number(hunk[1]);
286
+ inHunk = true;
240
287
  continue;
241
288
  }
242
- if (current && raw.startsWith("+")) {
289
+ if (current && inHunk && raw.startsWith("+")) {
243
290
  current.lines.push({ line: next, text: raw.slice(1) });
244
291
  next += 1;
245
292
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * A System secret in the session's own change, taken out by the session
3
+ * before it ends (YAG-1209). A yak's machine holds its System's values
4
+ * (`../placedValues.ts`), and the host never pushes a change that holds one
5
+ * of the secrets among them: that refusal hands the push to a person. So
6
+ * before a writing turn ends, its change is read for each secret's value. One
7
+ * there is named to the model by variable and place, never by value, and the
8
+ * model is asked once, in the same session, to read it from the environment
9
+ * instead and finish. A secret still there after that is left for the host's
10
+ * refusal, the backstop, and the turn's result says so by name.
11
+ *
12
+ * What is read: the change's added lines and new files (the tree's dirt from
13
+ * before the turn left out, as `changeScan.ts` leaves it), every path it
14
+ * touched, each commit's own patch past the turn's start (a value one commit
15
+ * added and a later one took out is still pushed), and their messages.
16
+ *
17
+ * Only exact text is found, as on the host: a value the session encoded
18
+ * first gets past both.
19
+ */
20
+ import { type PlacedSecret, type PlacedValues } from "../placedValues.js";
21
+ import type { StageResult } from "./types.js";
22
+ import type { WorktreeExec } from "./worktree.js";
23
+ /** One secret the change holds, and where; never its value. */
24
+ export interface PlacedSecretHit {
25
+ name: string;
26
+ /** The change's files that hold it in their text or their path, each path with any value marked. */
27
+ files: string[];
28
+ /** A commit past the start holds it, whether or not the change still does: the branch needs rewriting. */
29
+ committed: boolean;
30
+ /** A commit message holds it. */
31
+ message: boolean;
32
+ /**
33
+ * Another repository of a yak's System the session changed in place
34
+ * (YAG-1211), where the hit is: its `owner/name`, its folder and the
35
+ * turn's start there. Absent: the session's own repository.
36
+ */
37
+ elsewhere?: {
38
+ repository: string;
39
+ dir: string;
40
+ base: string;
41
+ };
42
+ }
43
+ /** Another repository of a yak's System, checked out beside the session's own (YAG-1211). */
44
+ export interface OtherRepositoryScan {
45
+ /** `owner/name`. */
46
+ repository: string;
47
+ /** Its working copy. */
48
+ cwd: string;
49
+ /** Its head when the turn started; null when it could not be read (not scanned). */
50
+ base: string | null;
51
+ /** Its dirt from before the turn. */
52
+ skip?: readonly string[];
53
+ }
54
+ /**
55
+ * Where the host's push of another repository of a yak's System starts, as
56
+ * its collection reads it (`attempts/repositoryWork.ts`, `workStartOf` and
57
+ * `remoteBaseOf`), so the session reads every commit that push publishes:
58
+ * the head the attempt last pushed there, when the checkout descends from
59
+ * it; else, on the attempt's own branch, the newest commit of it GitHub has
60
+ * (an earlier turn's work, never pushed, is published too); else where the
61
+ * turn found it. Read when the turn starts, before the session moves it.
62
+ */
63
+ export declare function publicationBase(exec: WorktreeExec, cwd: string, input: {
64
+ head: string;
65
+ pushedHead: string | null;
66
+ branch: string | null;
67
+ }, signal?: AbortSignal): Promise<string>;
68
+ export interface PlacedSecretScanOpts {
69
+ exec: WorktreeExec;
70
+ /** The tree's dirt from before the turn (`git status` paths, a folder ending in `/`): not the turn's. */
71
+ skip?: readonly string[];
72
+ signal?: AbortSignal;
73
+ readFile?: (path: string) => Buffer;
74
+ }
75
+ /**
76
+ * Each secret the change past `base` holds, or null when git could not say
77
+ * what changed (the read that failed is logged). The value never leaves this
78
+ * function.
79
+ */
80
+ export declare function placedSecretsInChange(cwd: string, base: string, secrets: readonly PlacedSecret[], opts: PlacedSecretScanOpts): Promise<PlacedSecretHit[] | null>;
81
+ /** The ask: each secret by name and place, what to do instead, and to finish as before. */
82
+ export declare function placedSecretAsk(hits: readonly PlacedSecretHit[], base: string): string;
83
+ export interface PlacedSecretHeal {
84
+ /** The turn's last run: the ask's, when it ran to its end. */
85
+ run: StageResult;
86
+ /** The ask's run, when there was one. */
87
+ asked: StageResult[];
88
+ /** For the turn's result: a secret the change still holds, by name, or a scan that could not read it. */
89
+ note: string | null;
90
+ }
91
+ /**
92
+ * Reads a writing turn's change for the System's secrets and, when it holds
93
+ * one, asks the model once to take it out and finish. Not asked of a turn
94
+ * that was stopped, ran out of time or ended in an error, nor on a machine
95
+ * with no secret placed.
96
+ */
97
+ export declare function healPlacedSecrets(run: StageResult, turn: (message: string) => Promise<StageResult>, opts: PlacedSecretScanOpts & {
98
+ cwd: string;
99
+ base: string | null;
100
+ store: PlacedValues | null;
101
+ /** A yak's System's other repositories the session may change in place (YAG-1211), each read as its own. */
102
+ others?: readonly OtherRepositoryScan[];
103
+ }): Promise<PlacedSecretHeal>;
104
+ //# sourceMappingURL=placedValueHeal.d.ts.map
@@ -0,0 +1,263 @@
1
+ /**
2
+ * A System secret in the session's own change, taken out by the session
3
+ * before it ends (YAG-1209). A yak's machine holds its System's values
4
+ * (`../placedValues.ts`), and the host never pushes a change that holds one
5
+ * of the secrets among them: that refusal hands the push to a person. So
6
+ * before a writing turn ends, its change is read for each secret's value. One
7
+ * there is named to the model by variable and place, never by value, and the
8
+ * model is asked once, in the same session, to read it from the environment
9
+ * instead and finish. A secret still there after that is left for the host's
10
+ * refusal, the backstop, and the turn's result says so by name.
11
+ *
12
+ * What is read: the change's added lines and new files (the tree's dirt from
13
+ * before the turn left out, as `changeScan.ts` leaves it), every path it
14
+ * touched, each commit's own patch past the turn's start (a value one commit
15
+ * added and a later one took out is still pushed), and their messages.
16
+ *
17
+ * Only exact text is found, as on the host: a value the session encoded
18
+ * first gets past both.
19
+ */
20
+ import { readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { logEvent } from "../errorSink.js";
23
+ import { PLACED_VALUE_MARK } from "../placedValues.js";
24
+ import { addedTextOfDiff } from "./changeScan.js";
25
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
26
+ /** At most this many commits of its own a checkout is read for, as the host reads it. */
27
+ const MAX_OWN_COMMITS = 500;
28
+ /**
29
+ * Where the host's push of another repository of a yak's System starts, as
30
+ * its collection reads it (`attempts/repositoryWork.ts`, `workStartOf` and
31
+ * `remoteBaseOf`), so the session reads every commit that push publishes:
32
+ * the head the attempt last pushed there, when the checkout descends from
33
+ * it; else, on the attempt's own branch, the newest commit of it GitHub has
34
+ * (an earlier turn's work, never pushed, is published too); else where the
35
+ * turn found it. Read when the turn starts, before the session moves it.
36
+ */
37
+ export async function publicationBase(exec, cwd, input, signal) {
38
+ const git = (args) => exec(["git", ...args], cwd, signal);
39
+ if (input.pushedHead && SHA.test(input.pushedHead)) {
40
+ const descends = await git(["merge-base", "--is-ancestor", input.pushedHead, input.head]);
41
+ if (descends.code === 0)
42
+ return input.pushedHead;
43
+ }
44
+ if (!input.branch)
45
+ return input.head;
46
+ const on = await git(["symbolic-ref", "-q", "--short", "HEAD"]);
47
+ if (on.code !== 0 || on.output.trim() !== input.branch)
48
+ return input.head;
49
+ const own = await git(["rev-list", "--count", input.head, "--not", "--remotes"]);
50
+ const count = Number(own.output.trim());
51
+ if (own.code !== 0 || !Number.isInteger(count) || count === 0 || count > MAX_OWN_COMMITS) {
52
+ return input.head;
53
+ }
54
+ const boundary = await git(["rev-list", "--boundary", input.head, "--not", "--remotes"]);
55
+ if (boundary.code !== 0)
56
+ return input.head;
57
+ const bases = [
58
+ ...new Set(boundary.output
59
+ .split("\n")
60
+ .filter((line) => line.startsWith("-"))
61
+ .map((line) => line.slice(1).trim())),
62
+ ];
63
+ // One commit below them all, as the host takes it; else only this turn's.
64
+ return bases.length === 1 && SHA.test(bases[0]) ? bases[0] : input.head;
65
+ }
66
+ /** How much of one new file is read: a value sits in source, not past the first megabyte. */
67
+ const MAX_READ_BYTES = 1024 * 1024;
68
+ /** Each named git read's output, or the first that failed, by name and exit code. */
69
+ async function readAll(reads) {
70
+ const names = Object.keys(reads);
71
+ const results = await Promise.all(names.map((name) => reads[name]));
72
+ const out = {};
73
+ for (const [at, name] of names.entries()) {
74
+ const result = results[at];
75
+ if (result.code !== 0)
76
+ return { failed: name, code: result.code };
77
+ out[name] = result.output;
78
+ }
79
+ return out;
80
+ }
81
+ /**
82
+ * Each secret the change past `base` holds, or null when git could not say
83
+ * what changed (the read that failed is logged). The value never leaves this
84
+ * function.
85
+ */
86
+ export async function placedSecretsInChange(cwd, base, secrets, opts) {
87
+ if (secrets.length === 0)
88
+ return [];
89
+ const skipFiles = new Set((opts.skip ?? []).filter((path) => !path.endsWith("/")));
90
+ const skipDirs = (opts.skip ?? []).filter((path) => path.endsWith("/"));
91
+ const skipped = (path) => skipFiles.has(path) || skipDirs.some((dir) => path.startsWith(dir));
92
+ const git = (args) => opts.exec(["git", "-c", "core.quotepath=off", ...args], cwd, opts.signal);
93
+ const range = `${base}..HEAD`;
94
+ // Each commit's own patch, as the host's push reads it: a merge's by what
95
+ // it changed beyond merging (`remerge`), and one of three parents or more,
96
+ // which `remerge` shows nothing for, against its first parent.
97
+ const patch = ["--format=", "-p", "-U0", "--text", "--no-color", "--no-ext-diff"];
98
+ const remerge = "--diff-merges=remerge";
99
+ const octopus = ["--min-parents=3", "--diff-merges=first-parent"];
100
+ const read = await readAll({
101
+ diff: git(["diff", base, "-U0", "--no-color", "--no-renames", "--no-ext-diff", "--text"]),
102
+ changedPaths: git(["diff", base, "--name-only", "-z", "--no-renames"]),
103
+ others: git(["ls-files", "--others", "--exclude-standard", "-z"]),
104
+ merged: git(["log", remerge, ...patch, range]),
105
+ octopusMerged: git(["log", ...octopus, ...patch, range]),
106
+ mergedPaths: git(["log", remerge, "--format=", "--name-only", "-z", range]),
107
+ octopusPaths: git(["log", ...octopus, "--format=", "--name-only", "-z", range]),
108
+ messages: git(["log", "--format=%B%x00", range]),
109
+ });
110
+ if ("failed" in read) {
111
+ logEvent({
112
+ source: "placed-values",
113
+ level: "warn",
114
+ event: "heal_scan_unread",
115
+ fields: { read: read.failed, exitCode: read.code },
116
+ });
117
+ return null;
118
+ }
119
+ const { diff, changedPaths, others, messages } = read;
120
+ const history = `${read.merged}\n${read.octopusMerged}`;
121
+ const historyPaths = `${read.mergedPaths}\0${read.octopusPaths}`;
122
+ const split = (text) => text.split("\0").filter(Boolean);
123
+ const texts = addedTextOfDiff(diff)
124
+ .filter((file) => !skipped(file.path))
125
+ .map((file) => ({ path: file.path, text: file.lines.map((line) => line.text).join("\n") }));
126
+ const readFile = opts.readFile ?? ((path) => readFileSync(path));
127
+ for (const path of split(others)) {
128
+ if (skipped(path))
129
+ continue;
130
+ try {
131
+ texts.push({
132
+ path,
133
+ text: readFile(join(cwd, path)).subarray(0, MAX_READ_BYTES).toString("utf8"),
134
+ });
135
+ }
136
+ catch {
137
+ // A file gone since git listed it holds nothing to push.
138
+ }
139
+ }
140
+ const paths = [...split(changedPaths), ...split(others)].filter((path) => !skipped(path));
141
+ const historyText = addedTextOfDiff(history)
142
+ .map((file) => file.lines.map((line) => line.text).join("\n"))
143
+ .join("\n");
144
+ // A path is shown with every secret out of it, the longest first, never
145
+ // only the one it is named for.
146
+ const longestFirst = [...secrets].sort((a, b) => b.value.length - a.value.length);
147
+ const shown = (path) => longestFirst.reduce((out, { value }) => out.split(value).join(PLACED_VALUE_MARK), path);
148
+ const hits = [];
149
+ const named = new Set();
150
+ for (const { name, value } of secrets) {
151
+ if (named.has(name))
152
+ continue;
153
+ const files = [
154
+ ...new Set([
155
+ ...texts.filter((file) => file.text.includes(value)).map((file) => file.path),
156
+ ...paths.filter((path) => path.includes(value)),
157
+ ]),
158
+ ].map(shown);
159
+ // A commit that holds it is pushed even once the tree no longer does.
160
+ const committed = historyText.includes(value) || split(historyPaths).some((path) => path.includes(value));
161
+ const message = messages.includes(value);
162
+ if (files.length === 0 && !committed && !message)
163
+ continue;
164
+ named.add(name);
165
+ hits.push({ name, files, committed, message });
166
+ }
167
+ return hits;
168
+ }
169
+ /** `a`, `a and b`, `a, b and c`. */
170
+ function listed(items) {
171
+ return items.length < 2
172
+ ? (items[0] ?? "")
173
+ : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
174
+ }
175
+ /** The ask: each secret by name and place, what to do instead, and to finish as before. */
176
+ export function placedSecretAsk(hits, base) {
177
+ const rewrite = hits.some((hit) => hit.committed || hit.message);
178
+ // Each repository whose commits hold one, by the command that rewrites them there.
179
+ const resets = [
180
+ ...new Set(hits
181
+ .filter((hit) => hit.committed || hit.message)
182
+ .map((hit) => hit.elsewhere
183
+ ? `\`git -C ${hit.elsewhere.dir} reset --soft ${hit.elsewhere.base}\` in ${hit.elsewhere.repository}`
184
+ : `\`git reset --soft ${base}\``)),
185
+ ];
186
+ return [
187
+ "Your change holds the value of a System credential, and YAGNI never pushes a change that holds one:",
188
+ ...hits.map((hit) => {
189
+ const places = [
190
+ ...hit.files.map((file) => `\`${file}\``),
191
+ ...(hit.committed
192
+ ? [`${hit.files.length ? "a" : "an earlier"} commit on this branch`]
193
+ : []),
194
+ ...(hit.message ? ["a commit message"] : []),
195
+ ];
196
+ return `- ${hit.name}, in ${listed(places)}${hit.elsewhere ? ` in ${hit.elsewhere.repository} (\`${hit.elsewhere.dir}\`)` : ""}`;
197
+ }),
198
+ "",
199
+ "Take each one out. Where the code needs it, read it from the environment instead " +
200
+ `(\`process.env.${hits[0].name}\`, \`os.environ["${hits[0].name}"]\`), and in a test use an obvious fake. ` +
201
+ `You cannot see the value: what you read shows it as ${PLACED_VALUE_MARK}, so find the line by what is ` +
202
+ "around it, or write the file again whole. Never read /run/yagni/env, or print a value, to find it.",
203
+ rewrite
204
+ ? `A commit on this branch holds it too, and every commit is pushed: rewrite this branch's commits so that none of them, and no message, holds it (for example ${listed(resets)} once the files are fixed, then commit again).`
205
+ : "Then commit.",
206
+ "Then end your turn as before, with your report.",
207
+ ].join("\n");
208
+ }
209
+ /**
210
+ * Reads a writing turn's change for the System's secrets and, when it holds
211
+ * one, asks the model once to take it out and finish. Not asked of a turn
212
+ * that was stopped, ran out of time or ended in an error, nor on a machine
213
+ * with no secret placed.
214
+ */
215
+ export async function healPlacedSecrets(run, turn, opts) {
216
+ const unchanged = { run, asked: [], note: null };
217
+ const { store, base } = opts;
218
+ if (!store || !base || opts.signal?.aborted || run.timedOut || run.exitCode !== 0) {
219
+ return unchanged;
220
+ }
221
+ const scanOne = (cwd, from, skip) => placedSecretsInChange(cwd, from, store.secrets(), { ...opts, skip }).catch(() => null);
222
+ // The session's own repository, then each other one it may have changed:
223
+ // null when any of them could not be read.
224
+ const scan = async () => {
225
+ const own = await scanOne(opts.cwd, base, opts.skip);
226
+ if (own === null)
227
+ return null;
228
+ const hits = [...own];
229
+ for (const other of opts.others ?? []) {
230
+ if (!other.base)
231
+ continue;
232
+ const found = await scanOne(other.cwd, other.base, other.skip);
233
+ if (found === null)
234
+ return null;
235
+ const elsewhere = { repository: other.repository, dir: other.cwd, base: other.base };
236
+ hits.push(...found.map((hit) => ({ ...hit, elsewhere })));
237
+ }
238
+ return hits;
239
+ };
240
+ const unread = "The change could not be read for the System's credentials before the turn ended; the host still checks its push.";
241
+ const hits = await scan();
242
+ if (hits === null)
243
+ return { ...unchanged, note: unread };
244
+ if (hits.length === 0)
245
+ return unchanged;
246
+ const again = await turn(placedSecretAsk(hits, base));
247
+ const left = await scan();
248
+ return {
249
+ run: again.exitCode === 0 ? again : run,
250
+ asked: [again],
251
+ note: left === null ? unread : stillThereNote(left),
252
+ };
253
+ }
254
+ /** The result's note for secrets still in the change after the ask, by name; null when none is. */
255
+ function stillThereNote(left) {
256
+ if (left.length === 0)
257
+ return null;
258
+ // One name once, though more than one repository holds it.
259
+ const names = [...new Set(left.map((hit) => hit.name))];
260
+ const them = names.length > 1 ? "them" : "it";
261
+ return `The change still holds the System's ${listed(names)} after one ask to take ${them} out: YAGNI will not push it, and a person is asked.`;
262
+ }
263
+ //# sourceMappingURL=placedValueHeal.js.map
@@ -38,6 +38,7 @@
38
38
  * kept: the review loop and its round cap, the fixer, and the plan stage's
39
39
  * own clock.
40
40
  */
41
+ import { type PlacedValues } from "../placedValues.js";
41
42
  import { type AttemptResult, type CloudIdentity, type CloudStage } from "./cloud.js";
42
43
  import type { ContinuationInputs } from "./continuation.js";
43
44
  import { type PlanChange } from "./planChanges.js";
@@ -97,6 +98,20 @@ export interface TurnFacts {
97
98
  export declare const NEXT_STEP_NOTE_FILE_NAME = "next-step-note.md";
98
99
  /** The file the host writes a yak's new messages to (`attempts/inputs.ts`, `yaks/turns.ts`). */
99
100
  export declare const NEW_SINCE_LAST_TURN_FILE_NAME = "new-since-last-turn.md";
101
+ /** The file the host names a yak's System's other repositories in (`attempts/inputs.ts`, YAG-1211). */
102
+ export declare const SYSTEM_REPOSITORIES_FILE_NAME = "system-repositories.json";
103
+ /**
104
+ * The System's other repositories the host named, by `owner/name` and
105
+ * folder (an absolute path, never the session's own), each with the head
106
+ * the attempt last pushed there and the attempt's branch; none when the
107
+ * file is absent or does not parse.
108
+ */
109
+ export declare function systemRepositoriesOf(text: string | null, cwd: string): Array<{
110
+ repository: string;
111
+ dir: string;
112
+ pushedHead: string | null;
113
+ branch: string | null;
114
+ }>;
100
115
  /** The one message a turn sends the session. Pure. */
101
116
  export declare function turnMessage(facts: TurnFacts): string;
102
117
  /** The model's own account of a turn that builds (`session-report.json`). */
@@ -176,6 +191,8 @@ export interface SessionTurnDeps {
176
191
  rss: number;
177
192
  heapUsed: number;
178
193
  };
194
+ /** A yak's placed values (YAG-1209); absent, read from the machine, null on any other. */
195
+ placedValues?: PlacedValues | null;
179
196
  }
180
197
  export interface SessionTurnOutcome {
181
198
  /** A written plan, or a clean turn whose branch carries the attempt's committed work. */
@@ -40,13 +40,15 @@
40
40
  */
41
41
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
42
42
  import { homedir } from "node:os";
43
- import { join, relative } from "node:path";
43
+ import { isAbsolute, join, relative } from "node:path";
44
+ import { openPlacedValues } from "../placedValues.js";
44
45
  import { scanChange } from "./changeScan.js";
45
46
  import { completeCloudSession, RESULT_FILE_NAME, } from "./cloud.js";
46
47
  import { finishExec } from "./finish.js";
47
48
  import { MISSION_CHECKS_FILE_NAME, readMissionChecksFile } from "./missionChecks.js";
48
49
  import { creditExhaustionReason } from "./orchestrator.js";
49
50
  import { WORK_A_TICKET_SKILL } from "./personas.js";
51
+ import { healPlacedSecrets, publicationBase } from "./placedValueHeal.js";
50
52
  import { extractPlanJson } from "./planOutput.js";
51
53
  import { PLAN_CHANGES_RULE, parsePlanChanges, planChangeNote, } from "./planChanges.js";
52
54
  import { runStage as defaultRunStage } from "./runner.js";
@@ -116,6 +118,37 @@ function feedStage(stage) {
116
118
  export const NEXT_STEP_NOTE_FILE_NAME = "next-step-note.md";
117
119
  /** The file the host writes a yak's new messages to (`attempts/inputs.ts`, `yaks/turns.ts`). */
118
120
  export const NEW_SINCE_LAST_TURN_FILE_NAME = "new-since-last-turn.md";
121
+ /** The file the host names a yak's System's other repositories in (`attempts/inputs.ts`, YAG-1211). */
122
+ export const SYSTEM_REPOSITORIES_FILE_NAME = "system-repositories.json";
123
+ /**
124
+ * The System's other repositories the host named, by `owner/name` and
125
+ * folder (an absolute path, never the session's own), each with the head
126
+ * the attempt last pushed there and the attempt's branch; none when the
127
+ * file is absent or does not parse.
128
+ */
129
+ export function systemRepositoriesOf(text, cwd) {
130
+ if (!text)
131
+ return [];
132
+ try {
133
+ const parsed = JSON.parse(text);
134
+ const branch = typeof parsed.branch === "string" && parsed.branch ? parsed.branch : null;
135
+ if (!Array.isArray(parsed.repositories))
136
+ return [];
137
+ return parsed.repositories.flatMap((entry) => {
138
+ const { fullName, dir, pushedHead } = (entry ?? {});
139
+ if (typeof fullName !== "string" || typeof dir !== "string")
140
+ return [];
141
+ if (!isAbsolute(dir) || dir.includes("..") || dir === cwd)
142
+ return [];
143
+ const pushed = typeof pushedHead === "string" && SHA.test(pushedHead) ? pushedHead : null;
144
+ return [{ repository: fullName, dir, pushedHead: pushed, branch }];
145
+ });
146
+ }
147
+ catch {
148
+ return [];
149
+ }
150
+ }
151
+ const SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
119
152
  const REPORT_CONTRACT = (outDir) => `Last, write ${join(outDir, SESSION_REPORT_FILE_NAME)} as JSON, honestly: ` +
120
153
  '{"summary": "<what you changed, in two or three sentences>", ' +
121
154
  '"checks": [{"name": "lint", "command": "pnpm lint", "cwd": ".", "exitCode": 0, "durationMs": 41000, ' +
@@ -481,6 +514,25 @@ async function runTurn(input, deps, pulse) {
481
514
  const baseSha = start.head;
482
515
  const preRunDirt = parseChangedPaths(start.status);
483
516
  const writes = input.stage !== "plan";
517
+ // A yak's System's other repositories, each as the turn found it, for the
518
+ // read of a writing turn's change for a placed secret (YAG-1211).
519
+ const others = [];
520
+ if (writes) {
521
+ const listed = systemRepositoriesOf(readOrNull(join(input.inputDir, SYSTEM_REPOSITORIES_FILE_NAME)), input.cwd);
522
+ for (const { repository, dir, pushedHead, branch } of listed) {
523
+ const found = await snapshot(dir, input.signal);
524
+ others.push({
525
+ repository,
526
+ cwd: dir,
527
+ // Where the host's push there starts, so an earlier turn's commits it
528
+ // will publish are read too, never only this turn's.
529
+ base: found.tracked
530
+ ? await publicationBase(exec, dir, { head: found.head, pushedHead, branch }, input.signal)
531
+ : null,
532
+ skip: parseChangedPaths(found.status),
533
+ });
534
+ }
535
+ }
484
536
  const stageId = feedStage(input.stage);
485
537
  const timeBudgetMs = input.deadlineMs === undefined
486
538
  ? undefined
@@ -553,6 +605,23 @@ async function runTurn(input, deps, pulse) {
553
605
  try {
554
606
  let run = await turn(message);
555
607
  stages.push(run);
608
+ if (writes) {
609
+ // A System secret in the change is taken out in this session, before
610
+ // the host's push would stop on it for a person (YAG-1209).
611
+ const healed = await healPlacedSecrets(run, turn, {
612
+ cwd: input.cwd,
613
+ base: baseSha,
614
+ store: deps.placedValues === undefined ? openPlacedValues() : deps.placedValues,
615
+ exec,
616
+ skip: preRunDirt,
617
+ others,
618
+ ...(input.signal ? { signal: input.signal } : {}),
619
+ });
620
+ stages.push(...healed.asked);
621
+ run = healed.run;
622
+ if (healed.note)
623
+ notes.push(healed.note);
624
+ }
556
625
  if (input.stage === "plan") {
557
626
  const planned = await planWithBlock(run, turn, input.signal);
558
627
  stages.push(...planned.asked);
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A yak's System places its provided values on the machine the session works
3
+ * on (YAG-1209): a tmpfs file, `/run/yagni/secret/env`, linked at
4
+ * `/run/yagni/env`, owned by the run user the session runs as, so the session
5
+ * can read it, and a running service's environment too. This module is the
6
+ * first of three precautions: it replaces each placed secret in what the
7
+ * model reads. Only the secrets count ({@link PLACED_SECRET_NAMES_FILE}: a
8
+ * credential the host's one change classifier calls a secret); test data
9
+ * and a public value the model reads as they are. The session is told never
10
+ * to read the file (`branding.ts`, `PLACED_VALUES_SECTION`), its finish asks
11
+ * the model to take a secret out of its change (`pipeline/placedValueHeal.ts`),
12
+ * and the host refuses a push that still holds one (the backend's
13
+ * `attempts/placedValues.ts`).
14
+ *
15
+ * It acts only where the file is: on any other machine {@link openPlacedValues}
16
+ * opens nothing and no handler registers, so every other session is unchanged.
17
+ * Where it is, three handlers run after every other one the extension adds:
18
+ * `tool_result` rewrites what a tool returns before the model reads it (and
19
+ * before the session file keeps it), `message_end` rewrites any other message
20
+ * before the session file keeps it (a background job's notification quotes
21
+ * the job's output tail, and pi's compaction and branch summaries read the
22
+ * saved session, never a model call's context), and `context` rewrites every
23
+ * message a model call carries, as the backstop. An assistant's own message
24
+ * is never rewritten: its thinking is signed.
25
+ *
26
+ * Honest scope: an exact match of each value in the forms it is printed in
27
+ * (raw, inside the file, as bash and JSON quote it). A value the session
28
+ * encodes first (base64, split, reversed), part of a value cut by a tool's
29
+ * truncation, and a value inside an image all get past.
30
+ */
31
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
+ /** Where the backend places the values (`repos/system/needs/placement.ts`, `SYSTEM_SECRET_FILE`). */
33
+ export declare const PLACED_VALUES_FILE = "/run/yagni/secret/env";
34
+ /** The link scripts source (`SYSTEM_ENV_PATH`). */
35
+ export declare const PLACED_VALUES_LINK = "/run/yagni/env";
36
+ /**
37
+ * The names of the placed values that are secrets, one per line, names only
38
+ * (`SYSTEM_SECRET_NAMES_FILE`): the host's one classifier picked them
39
+ * (`placedSecretsOf`, a credential its change scan calls a secret). Every
40
+ * other value (test data, a public URL) the model reads as it is. A machine
41
+ * whose values were placed without this file keeps every value from the model.
42
+ */
43
+ export declare const PLACED_SECRET_NAMES_FILE = "/run/yagni/secret/secret-names";
44
+ /**
45
+ * The shortest value replaced: the shortest a person can enter for a need
46
+ * (`SYSTEM_NEED_VALUE_MIN_LENGTH`), and the floor the host's redactors keep.
47
+ * Anything shorter (`postgres`, a port) would mangle ordinary output.
48
+ */
49
+ export declare const PLACED_VALUE_MIN_LENGTH = 8;
50
+ /** The host's own mark (`redactValues`), so the transcript reads the same on both sides. */
51
+ export declare const PLACED_VALUE_MARK = "[REDACTED]";
52
+ /**
53
+ * The values in the host's file: one `NAME='value'` line per value, a `'`
54
+ * inside written `'"'"'`, a value free to span lines. A line it cannot read
55
+ * is skipped.
56
+ */
57
+ export declare function parsePlacedEnvFile(text: string): Map<string, string>;
58
+ /**
59
+ * Every form a value is printed in, longest first: as it is, inside the
60
+ * host's file, as bash quotes it (`declare -p`, `set`, in single, double or
61
+ * ANSI-C quotes), and as JSON escapes it (`docker inspect`, `jq`, a
62
+ * multi-line key). Values under the floor are left out.
63
+ */
64
+ export declare function placedValueForms(values: Iterable<string>): string[];
65
+ /** `text` with every form replaced by the mark. */
66
+ export declare function redactPlacedText(text: string, forms: readonly string[]): string;
67
+ /** A secret the System placed, by the variable a person knows it as; never logged. */
68
+ export interface PlacedSecret {
69
+ name: string;
70
+ value: string;
71
+ }
72
+ /** The secrets this process has seen, read again at every check; never forgotten. */
73
+ export interface PlacedValues {
74
+ /** Reads the file again and returns every form of every secret seen so far. */
75
+ forms(): string[];
76
+ /**
77
+ * Reads the file again and returns every secret the host's list named so
78
+ * far, each by its first name: what the session is asked to take out of
79
+ * its change. A value kept from the model only because there is no list is
80
+ * never one, so a fixture's test data is never asked about.
81
+ */
82
+ secrets(): PlacedSecret[];
83
+ }
84
+ /**
85
+ * Opens the placed values when one of `paths` is there, else null (no file:
86
+ * not a yak's machine, and nothing should change). Only the secrets among
87
+ * them are kept from the model: those `namesPath` lists. A secret is kept
88
+ * for the life of the process, so a session that deletes the file and prints
89
+ * a copy is still covered, and one placed later is added. While there is no
90
+ * list (a placement from before it, or the list gone), every value read is
91
+ * kept from the model too, but only until a list is read: it is read again
92
+ * at every check, and test data and a public value then show as they are.
93
+ */
94
+ export declare function openPlacedValues(paths?: readonly string[], namesPath?: string | null): PlacedValues | null;
95
+ /**
96
+ * Registers the handlers. Call it after every other `tool_result`,
97
+ * `message_end`, `context` and `before_agent_start` handler the extension
98
+ * adds, so it sees what they append. Each message handler withholds what it
99
+ * could not check rather than pass it.
100
+ */
101
+ export declare function registerPlacedValueRedaction(pi: ExtensionAPI, store: PlacedValues): void;
102
+ //# sourceMappingURL=placedValues.d.ts.map
@@ -0,0 +1,462 @@
1
+ /**
2
+ * A yak's System places its provided values on the machine the session works
3
+ * on (YAG-1209): a tmpfs file, `/run/yagni/secret/env`, linked at
4
+ * `/run/yagni/env`, owned by the run user the session runs as, so the session
5
+ * can read it, and a running service's environment too. This module is the
6
+ * first of three precautions: it replaces each placed secret in what the
7
+ * model reads. Only the secrets count ({@link PLACED_SECRET_NAMES_FILE}: a
8
+ * credential the host's one change classifier calls a secret); test data
9
+ * and a public value the model reads as they are. The session is told never
10
+ * to read the file (`branding.ts`, `PLACED_VALUES_SECTION`), its finish asks
11
+ * the model to take a secret out of its change (`pipeline/placedValueHeal.ts`),
12
+ * and the host refuses a push that still holds one (the backend's
13
+ * `attempts/placedValues.ts`).
14
+ *
15
+ * It acts only where the file is: on any other machine {@link openPlacedValues}
16
+ * opens nothing and no handler registers, so every other session is unchanged.
17
+ * Where it is, three handlers run after every other one the extension adds:
18
+ * `tool_result` rewrites what a tool returns before the model reads it (and
19
+ * before the session file keeps it), `message_end` rewrites any other message
20
+ * before the session file keeps it (a background job's notification quotes
21
+ * the job's output tail, and pi's compaction and branch summaries read the
22
+ * saved session, never a model call's context), and `context` rewrites every
23
+ * message a model call carries, as the backstop. An assistant's own message
24
+ * is never rewritten: its thinking is signed.
25
+ *
26
+ * Honest scope: an exact match of each value in the forms it is printed in
27
+ * (raw, inside the file, as bash and JSON quote it). A value the session
28
+ * encodes first (base64, split, reversed), part of a value cut by a tool's
29
+ * truncation, and a value inside an image all get past.
30
+ */
31
+ import { readFileSync, statSync } from "node:fs";
32
+ import { logEvent } from "./errorSink.js";
33
+ /** Where the backend places the values (`repos/system/needs/placement.ts`, `SYSTEM_SECRET_FILE`). */
34
+ export const PLACED_VALUES_FILE = "/run/yagni/secret/env";
35
+ /** The link scripts source (`SYSTEM_ENV_PATH`). */
36
+ export const PLACED_VALUES_LINK = "/run/yagni/env";
37
+ /**
38
+ * The names of the placed values that are secrets, one per line, names only
39
+ * (`SYSTEM_SECRET_NAMES_FILE`): the host's one classifier picked them
40
+ * (`placedSecretsOf`, a credential its change scan calls a secret). Every
41
+ * other value (test data, a public URL) the model reads as it is. A machine
42
+ * whose values were placed without this file keeps every value from the model.
43
+ */
44
+ export const PLACED_SECRET_NAMES_FILE = "/run/yagni/secret/secret-names";
45
+ /**
46
+ * The shortest value replaced: the shortest a person can enter for a need
47
+ * (`SYSTEM_NEED_VALUE_MIN_LENGTH`), and the floor the host's redactors keep.
48
+ * Anything shorter (`postgres`, a port) would mangle ordinary output.
49
+ */
50
+ export const PLACED_VALUE_MIN_LENGTH = 8;
51
+ /** The host's own mark (`redactValues`), so the transcript reads the same on both sides. */
52
+ export const PLACED_VALUE_MARK = "[REDACTED]";
53
+ /** The tmpfs is mounted at 1 MiB; a larger file is not the host's. */
54
+ const MAX_FILE_BYTES = 1024 * 1024;
55
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
56
+ const WITHHELD = "[The tool's output was withheld: it could not be checked for the System's placed values.]";
57
+ const WITHHELD_MESSAGE = "[This message was withheld: it could not be checked for the System's placed values.]";
58
+ /**
59
+ * The values in the host's file: one `NAME='value'` line per value, a `'`
60
+ * inside written `'"'"'`, a value free to span lines. A line it cannot read
61
+ * is skipped.
62
+ */
63
+ export function parsePlacedEnvFile(text) {
64
+ const values = new Map();
65
+ let at = 0;
66
+ while (at < text.length) {
67
+ const eq = text.indexOf("=", at);
68
+ const lineEnd = text.indexOf("\n", at);
69
+ const name = eq === -1 ? "" : text.slice(at, eq);
70
+ const read = NAME.test(name) && (lineEnd === -1 || eq < lineEnd) ? quotedValueAt(text, eq + 1) : null;
71
+ if (read)
72
+ values.set(name, read.value);
73
+ at = read ? read.next : lineEnd === -1 ? text.length : lineEnd + 1;
74
+ }
75
+ return values;
76
+ }
77
+ /**
78
+ * The quoted value that starts at `start` (`'a'"'"'b'`, free to span lines),
79
+ * and where the next line starts; null when the line is not one the host writes.
80
+ */
81
+ function quotedValueAt(text, start) {
82
+ if (start >= text.length || text[start] === "\n")
83
+ return null;
84
+ let cursor = start;
85
+ let value = "";
86
+ while (cursor < text.length && text[cursor] !== "\n") {
87
+ if (text.startsWith(`"'"`, cursor)) {
88
+ value += "'";
89
+ cursor += 3;
90
+ continue;
91
+ }
92
+ const close = text[cursor] === "'" ? text.indexOf("'", cursor + 1) : -1;
93
+ if (close === -1)
94
+ return null;
95
+ value += text.slice(cursor + 1, close);
96
+ cursor = close + 1;
97
+ }
98
+ return { value, next: cursor + 1 };
99
+ }
100
+ /** Bash's own names for the characters its ANSI-C quoting escapes (`ansic_quote`). */
101
+ const ANSI_C_NAMED = {
102
+ "\u001b": "\\E",
103
+ "\u0007": "\\a",
104
+ "\v": "\\v",
105
+ "\b": "\\b",
106
+ "\f": "\\f",
107
+ "\n": "\\n",
108
+ "\r": "\\r",
109
+ "\t": "\\t",
110
+ "\\": "\\\\",
111
+ "'": "\\'",
112
+ };
113
+ /** A value inside bash's `$'...'` (`declare -p` of a value with a newline or a control character). */
114
+ function ansiCQuoted(value) {
115
+ let out = "";
116
+ for (const char of value) {
117
+ const code = char.codePointAt(0);
118
+ const named = ANSI_C_NAMED[char];
119
+ if (named)
120
+ out += named;
121
+ else if (code < 0x20 || code === 0x7f)
122
+ out += `\\${code.toString(8).padStart(3, "0")}`;
123
+ else
124
+ out += char;
125
+ }
126
+ return out;
127
+ }
128
+ /**
129
+ * Every form a value is printed in, longest first: as it is, inside the
130
+ * host's file, as bash quotes it (`declare -p`, `set`, in single, double or
131
+ * ANSI-C quotes), and as JSON escapes it (`docker inspect`, `jq`, a
132
+ * multi-line key). Values under the floor are left out.
133
+ */
134
+ export function placedValueForms(values) {
135
+ const forms = new Set();
136
+ for (const value of values) {
137
+ if (value.length < PLACED_VALUE_MIN_LENGTH)
138
+ continue;
139
+ forms.add(value);
140
+ forms.add(value.replaceAll("'", `'"'"'`));
141
+ forms.add(value.replaceAll("'", `'\\''`));
142
+ forms.add(value.replace(/[\\"$`]/g, (char) => `\\${char}`));
143
+ forms.add(ansiCQuoted(value));
144
+ forms.add(JSON.stringify(value).slice(1, -1));
145
+ }
146
+ return [...forms].sort((a, b) => b.length - a.length);
147
+ }
148
+ /** `text` with every form replaced by the mark. */
149
+ export function redactPlacedText(text, forms) {
150
+ let out = text;
151
+ for (const form of forms) {
152
+ if (out.includes(form))
153
+ out = out.split(form).join(PLACED_VALUE_MARK);
154
+ }
155
+ return out;
156
+ }
157
+ /** The file's text, or null when it is not a regular file of the host's size. */
158
+ function readPlacedFile(path) {
159
+ try {
160
+ const stat = statSync(path);
161
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES)
162
+ return null;
163
+ return readFileSync(path, "utf8");
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ }
169
+ /** The names the host listed as secrets, or null when it listed none (a placement before the list). */
170
+ function readSecretNames(path) {
171
+ const text = path ? readPlacedFile(path) : null;
172
+ if (text === null)
173
+ return null;
174
+ return new Set(text
175
+ .split("\n")
176
+ .map((line) => line.trim())
177
+ .filter((line) => NAME.test(line)));
178
+ }
179
+ /**
180
+ * Opens the placed values when one of `paths` is there, else null (no file:
181
+ * not a yak's machine, and nothing should change). Only the secrets among
182
+ * them are kept from the model: those `namesPath` lists. A secret is kept
183
+ * for the life of the process, so a session that deletes the file and prints
184
+ * a copy is still covered, and one placed later is added. While there is no
185
+ * list (a placement from before it, or the list gone), every value read is
186
+ * kept from the model too, but only until a list is read: it is read again
187
+ * at every check, and test data and a public value then show as they are.
188
+ */
189
+ export function openPlacedValues(paths = [PLACED_VALUES_FILE, PLACED_VALUES_LINK], namesPath = PLACED_SECRET_NAMES_FILE) {
190
+ /** Each secret the list named, by value: never forgotten. */
191
+ const kept = new Map();
192
+ /** Every value read while there is no list: kept until a list is read. */
193
+ const unlisted = new Map();
194
+ let forms = [];
195
+ const all = () => new Map([...unlisted, ...kept]);
196
+ const read = () => {
197
+ let found = false;
198
+ const names = readSecretNames(namesPath);
199
+ // The list says what is a secret: whatever it does not name shows again.
200
+ if (names !== null)
201
+ unlisted.clear();
202
+ for (const path of paths) {
203
+ const text = readPlacedFile(path);
204
+ if (text === null)
205
+ continue;
206
+ found = true;
207
+ for (const [name, value] of parsePlacedEnvFile(text)) {
208
+ if (names === null)
209
+ unlisted.set(value, name);
210
+ else if (names.has(name) && !kept.has(value))
211
+ kept.set(value, name);
212
+ }
213
+ }
214
+ // A handful of values: their forms are made again at each check.
215
+ forms = placedValueForms(all().keys());
216
+ return found;
217
+ };
218
+ if (!read())
219
+ return null;
220
+ return {
221
+ forms: () => {
222
+ read();
223
+ return forms;
224
+ },
225
+ secrets: () => {
226
+ read();
227
+ return [...kept].map(([value, name]) => ({ name, value }));
228
+ },
229
+ };
230
+ }
231
+ /** The parts with each text part's values replaced; the same array when nothing changed. */
232
+ function redactParts(parts, forms) {
233
+ let changed = false;
234
+ const next = parts.map((part) => {
235
+ if (part?.type !== "text" || typeof part.text !== "string")
236
+ return part;
237
+ const text = redactPlacedText(part.text, forms);
238
+ if (text === part.text)
239
+ return part;
240
+ changed = true;
241
+ return { ...part, text };
242
+ });
243
+ return changed ? next : parts;
244
+ }
245
+ /** String or parts, as a user or custom message carries its content. */
246
+ function redactContent(content, forms) {
247
+ if (typeof content === "string")
248
+ return redactPlacedText(content, forms);
249
+ return (Array.isArray(content) ? redactParts(content, forms) : content);
250
+ }
251
+ /** How deep {@link redactDetails} walks: a tool's details are a few levels of plain data. */
252
+ const MAX_DETAILS_DEPTH = 8;
253
+ /**
254
+ * A tool result's `details` with each string's secrets replaced: plain
255
+ * objects and arrays walked, anything else left as it is. The model never
256
+ * reads them, but the session saves them (the edit tool's `diff` and
257
+ * `patch` quote the lines around an edit). The same value when nothing changed.
258
+ */
259
+ function redactDetails(value, forms, depth = 0) {
260
+ if (typeof value === "string")
261
+ return redactPlacedText(value, forms);
262
+ if (depth >= MAX_DETAILS_DEPTH || value === null || typeof value !== "object")
263
+ return value;
264
+ if (Array.isArray(value)) {
265
+ const next = value.map((item) => redactDetails(item, forms, depth + 1));
266
+ return next.some((item, at) => item !== value[at]) ? next : value;
267
+ }
268
+ const proto = Object.getPrototypeOf(value);
269
+ if (proto !== Object.prototype && proto !== null)
270
+ return value;
271
+ let changed = false;
272
+ const next = {};
273
+ for (const [key, item] of Object.entries(value)) {
274
+ next[key] = redactDetails(item, forms, depth + 1);
275
+ if (next[key] !== item)
276
+ changed = true;
277
+ }
278
+ return changed ? next : value;
279
+ }
280
+ /** One message with its values replaced; the same object when nothing changed. Never an assistant's. */
281
+ function redactMessage(message, forms) {
282
+ const m = message;
283
+ switch (m.role) {
284
+ case "user":
285
+ case "custom":
286
+ case "toolResult": {
287
+ const content = m.content === undefined ? undefined : redactContent(m.content, forms);
288
+ const details = redactDetails(m.details, forms);
289
+ return content === m.content && details === m.details
290
+ ? message
291
+ : {
292
+ ...m,
293
+ ...(content !== undefined ? { content } : {}),
294
+ ...(details !== undefined ? { details } : {}),
295
+ };
296
+ }
297
+ case "bashExecution": {
298
+ if (typeof m.output !== "string")
299
+ return message;
300
+ const output = redactPlacedText(m.output, forms);
301
+ return output === m.output ? message : { ...m, output };
302
+ }
303
+ case "compactionSummary":
304
+ case "branchSummary": {
305
+ if (typeof m.summary !== "string")
306
+ return message;
307
+ const summary = redactPlacedText(m.summary, forms);
308
+ return summary === m.summary ? message : { ...m, summary };
309
+ }
310
+ default:
311
+ return message;
312
+ }
313
+ }
314
+ /**
315
+ * One message with its text withheld, for one that could not be checked: the
316
+ * same text-bearing fields {@link redactMessage} rewrites, `details` dropped.
317
+ * Never an assistant's.
318
+ */
319
+ function withheldMessage(message) {
320
+ switch (message.role) {
321
+ case "user":
322
+ case "custom":
323
+ case "toolResult": {
324
+ const { details: _unchecked, ...rest } = message;
325
+ return { ...rest, content: [{ type: "text", text: WITHHELD_MESSAGE }] };
326
+ }
327
+ case "bashExecution":
328
+ return { ...message, output: WITHHELD_MESSAGE };
329
+ case "compactionSummary":
330
+ case "branchSummary":
331
+ return { ...message, summary: WITHHELD_MESSAGE };
332
+ default:
333
+ return message;
334
+ }
335
+ }
336
+ /** The message redacted, or withheld when it could not be checked; never passed through unchecked. */
337
+ function checkedMessage(message, forms, event) {
338
+ try {
339
+ if (forms === null)
340
+ throw new Error("the placed values could not be read");
341
+ return redactMessage(message, forms);
342
+ }
343
+ catch (err) {
344
+ logEvent({
345
+ source: "placed-values",
346
+ level: "warn",
347
+ event,
348
+ fields: { role: message.role, errorClass: err instanceof Error ? err.name : typeof err },
349
+ });
350
+ return withheldMessage(message);
351
+ }
352
+ }
353
+ /**
354
+ * Every form, or null when they could not be read (a message is then
355
+ * withheld, not passed), the failure logged by its error's class.
356
+ */
357
+ function formsOf(store, handler) {
358
+ try {
359
+ return store.forms();
360
+ }
361
+ catch (err) {
362
+ logEvent({
363
+ source: "placed-values",
364
+ level: "warn",
365
+ event: "values_unread",
366
+ fields: { handler, errorClass: err instanceof Error ? err.name : typeof err },
367
+ });
368
+ return null;
369
+ }
370
+ }
371
+ /**
372
+ * Registers the handlers. Call it after every other `tool_result`,
373
+ * `message_end`, `context` and `before_agent_start` handler the extension
374
+ * adds, so it sees what they append. Each message handler withholds what it
375
+ * could not check rather than pass it.
376
+ */
377
+ export function registerPlacedValueRedaction(pi, store) {
378
+ pi.on("tool_result", (event) => {
379
+ try {
380
+ const forms = store.forms();
381
+ if (forms.length === 0)
382
+ return undefined;
383
+ const raw = event.content;
384
+ // The model never reads `details`, but the session saves them.
385
+ const details = redactDetails(event.details, forms);
386
+ const withDetails = details === event.details ? {} : { details };
387
+ if (typeof raw === "string") {
388
+ // Off pi's contract, but a tool that answers one string is still checked.
389
+ const text = redactPlacedText(raw, forms);
390
+ return text === raw && details === event.details
391
+ ? undefined
392
+ : { content: [{ type: "text", text }], ...withDetails };
393
+ }
394
+ if (!Array.isArray(event.content)) {
395
+ return details === event.details ? undefined : withDetails;
396
+ }
397
+ const content = redactParts(event.content, forms);
398
+ return content === event.content && details === event.details
399
+ ? undefined
400
+ : { content, ...withDetails };
401
+ }
402
+ catch (err) {
403
+ // Never pass through what could not be checked.
404
+ logEvent({
405
+ source: "placed-values",
406
+ level: "warn",
407
+ event: "tool_result_withheld",
408
+ fields: { errorClass: err instanceof Error ? err.name : typeof err },
409
+ });
410
+ // pi keeps a result's `details` unless a handler names new ones.
411
+ return { content: [{ type: "text", text: WITHHELD }], details: {} };
412
+ }
413
+ });
414
+ // A message is saved as `message_end` leaves it, and pi's compaction and
415
+ // branch summaries read the saved session, never the `context` pass below:
416
+ // a user or extension message that quotes a value (a background job's
417
+ // notice quotes its output) is saved replaced.
418
+ pi.on("message_end", (event) => {
419
+ const forms = formsOf(store, "message_end");
420
+ if (forms?.length === 0)
421
+ return undefined;
422
+ const message = checkedMessage(event.message, forms, "message_withheld");
423
+ return message === event.message ? undefined : { message };
424
+ });
425
+ pi.on("context", (event) => {
426
+ const forms = formsOf(store, "context");
427
+ if (forms?.length === 0 || !Array.isArray(event.messages))
428
+ return undefined;
429
+ let changed = false;
430
+ const messages = event.messages.map((message) => {
431
+ const next = checkedMessage(message, forms, "context_message_withheld");
432
+ if (next !== message)
433
+ changed = true;
434
+ return next;
435
+ });
436
+ return changed ? { messages } : undefined;
437
+ });
438
+ // The system prompt is not a message: pi builds it from the repository's
439
+ // own instruction files (AGENTS.md and the like), which could quote a
440
+ // secret, and this extension's branding. Registered after the branding, so
441
+ // it reads the prompt as sent.
442
+ pi.on("before_agent_start", (event) => {
443
+ if (typeof event.systemPrompt !== "string")
444
+ return undefined;
445
+ const forms = formsOf(store, "before_agent_start");
446
+ if (forms === null) {
447
+ // The one handler that does not fail closed: the prompt is the
448
+ // session's whole instructions, and withholding it would end the
449
+ // session. It goes as it is; `values_unread` above logs why.
450
+ logEvent({
451
+ source: "placed-values",
452
+ level: "warn",
453
+ event: "system_prompt_unchecked",
454
+ fields: {},
455
+ });
456
+ return undefined;
457
+ }
458
+ const systemPrompt = redactPlacedText(event.systemPrompt, forms);
459
+ return systemPrompt === event.systemPrompt ? undefined : { systemPrompt };
460
+ });
461
+ }
462
+ //# sourceMappingURL=placedValues.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yagni-app/code-staging",
3
- "version": "1.2.14-staging.2281.1",
3
+ "version": "1.2.14-staging.2283.1",
4
4
  "description": "YAGNI Code: a terminal coding agent that already knows your company. One YAGNI login routes the model and grounds the agent in your team's context.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "YAGNI, Inc. <jack@yagni.app> (https://yagni.app)",
@@ -58,5 +58,5 @@
58
58
  "turndown": "^7.2.4",
59
59
  "typebox": "^1.3.15"
60
60
  },
61
- "yagniSourceSha": "63e73bd85004c339d647aa5ce5f79c71527a9e89"
61
+ "yagniSourceSha": "070b30a13ecb2f930f932a574a84bc43a19f903b"
62
62
  }