flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/contracts/src/agents.rs

770 lines25,589 bytesCodeBlame
1//! Agents at work and what they remember. Kept by the work service.
2//!
3//! Every sandbox g1t starts for an agent is an [`AgentRun`]: what it is
4//! doing, on which pull request or issue, step by step, what it cost, and
5//! how it ended. People watch runs live, stop them and message them.
6//!
7//! Memory is what agents and people have learned that the next agent
8//! should know: about one project (its codebase), or about the whole
9//! workspace (true across its projects). It is members-only, is given to
10//! every g1t agent run, and never holds a secret.
11//!
12//! Each `*Args` struct is the argument of the method of the same name,
13//! served at `POST /rpc/<method>`.
14
15use serde::{Deserialize, Serialize};
16
17use crate::repos::RepoPath;
18use crate::work::{Pull, PullStatus, SessionEntry};
19use crate::{User, Viewer};
20
21/// The work an agent run does.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum RunKind {
25 /// Making the change an issue asks for.
26 Implement,
27 /// Addressing failed checks or a review on its own pull request.
28 Revise,
29 /// Reviewing someone's pull request.
30 Review,
31 /// Answering another agent's question or handoff.
32 Answer,
33 /// Merging in the branch a pull request will land on.
34 Update,
35 /// Turning an outcome into a plan of issues.
36 Plan,
37 /// Running an issue's acceptance checks. Not an agent: a sandbox.
38 Checks,
39 /// Building and checking a state of the merge queue. Not an agent.
40 Queue,
41 /// Finding out whether a pull request merges cleanly. Not an agent.
42 Mergecheck,
43}
44
45impl RunKind {
46 pub const ALL: [RunKind; 9] = [
47 RunKind::Implement,
48 RunKind::Revise,
49 RunKind::Review,
50 RunKind::Answer,
51 RunKind::Update,
52 RunKind::Plan,
53 RunKind::Checks,
54 RunKind::Queue,
55 RunKind::Mergecheck,
56 ];
57
58 pub fn as_str(self) -> &'static str {
59 match self {
60 RunKind::Implement => "implement",
61 RunKind::Revise => "revise",
62 RunKind::Review => "review",
63 RunKind::Answer => "answer",
64 RunKind::Update => "update",
65 RunKind::Plan => "plan",
66 RunKind::Checks => "checks",
67 RunKind::Queue => "queue",
68 RunKind::Mergecheck => "mergecheck",
69 }
70 }
71
72 pub fn parse(value: &str) -> Option<RunKind> {
73 RunKind::ALL.into_iter().find(|kind| kind.as_str() == value)
74 }
75
76 /// Whether a model does the work, rather than commands g1t runs.
77 pub fn is_agent(self) -> bool {
78 !matches!(self, RunKind::Checks | RunKind::Queue | RunKind::Mergecheck)
79 }
80
81 /// Whether a message reaches the agent while it runs: the harness asks
82 /// for messages after each tool call in these. Others read nothing new
83 /// until the next run on the same pull request.
84 pub fn takes_messages(self) -> bool {
85 matches!(self, RunKind::Implement | RunKind::Revise | RunKind::Answer)
86 }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "snake_case")]
91pub enum RunStatus {
92 /// Its sandbox is starting.
93 Queued,
94 Running,
95 Succeeded,
96 Failed,
97 /// A person stopped it.
98 Stopped,
99}
100
101impl RunStatus {
102 pub fn as_str(self) -> &'static str {
103 match self {
104 RunStatus::Queued => "queued",
105 RunStatus::Running => "running",
106 RunStatus::Succeeded => "succeeded",
107 RunStatus::Failed => "failed",
108 RunStatus::Stopped => "stopped",
109 }
110 }
111
112 pub fn parse(value: &str) -> Option<RunStatus> {
113 [
114 RunStatus::Queued,
115 RunStatus::Running,
116 RunStatus::Succeeded,
117 RunStatus::Failed,
118 RunStatus::Stopped,
119 ]
120 .into_iter()
121 .find(|status| status.as_str() == value)
122 }
123
124 pub fn is_active(self) -> bool {
125 matches!(self, RunStatus::Queued | RunStatus::Running)
126 }
127}
128
129/// One step of a run, as one short line.
130#[derive(Clone, Debug, Serialize, Deserialize)]
131pub struct RunStep {
132 /// RFC 3339.
133 pub at: String,
134 pub text: String,
135}
136
137/// One sandbox g1t started: an agent at work, or a run of checks.
138#[derive(Clone, Debug, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase")]
140pub struct AgentRun {
141 pub id: String,
142 pub repo: RepoPath,
143 /// The pull request it works on; for a plan, none.
144 pub number: Option<u32>,
145 /// That pull request's title, or the plan's brief.
146 pub title: Option<String>,
147 pub kind: RunKind,
148 /// Who is working: `g1t-agent` for g1t's own agent, `g1t` for a sandbox
149 /// that runs commands.
150 pub agent: String,
151 /// The model, by its public name. Members only.
152 pub model: Option<String>,
153 pub status: RunStatus,
154 /// What it is doing now, in one line.
155 pub step: Option<String>,
156 /// Every step so far, oldest first. Empty in lists.
157 #[serde(default)]
158 pub steps: Vec<RunStep>,
159 /// How many steps there are.
160 #[serde(default)]
161 pub step_count: u32,
162 /// Who put it to work, when a person did.
163 pub started_by: Option<String>,
164 /// Why it failed.
165 pub error: Option<String>,
166 /// What it cost, in US dollars, as the harness reported it. Members only.
167 pub cost_usd: Option<f64>,
168 pub turns: Option<u32>,
169 /// The most it may cost, in US dollars, from its guardrails. None: no
170 /// cap. Members only.
171 #[serde(default)]
172 pub budget_usd: Option<f64>,
173 /// The longest it may take, in minutes, from its guardrails.
174 #[serde(default)]
175 pub time_cap_minutes: Option<u32>,
176 /// `budget` or `time` when g1t stopped it for reaching a cap.
177 #[serde(default)]
178 pub halted: Option<String>,
179 /// RFC 3339.
180 pub created_at: String,
181 pub started_at: Option<String>,
182 pub finished_at: Option<String>,
183 pub updated_at: String,
184}
185
186/// What lets a sandbox, and nothing else, report on its run.
187#[derive(Clone, Debug, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase")]
189pub struct AgentRunTicket {
190 pub run_id: String,
191 pub token: String,
192}
193
194/// `open_run`: records a sandbox the runner is starting. Called by the
195/// runner service only. Returns `Outcome<AgentRunTicket>`.
196#[derive(Debug, Serialize, Deserialize)]
197#[serde(rename_all = "camelCase")]
198pub struct OpenRunArgs {
199 /// Who the sandbox acts as.
200 pub actor: User,
201 pub repo: RepoPath,
202 #[serde(default)]
203 pub number: Option<u32>,
204 #[serde(default)]
205 pub pull_id: Option<String>,
206 /// For a run with no pull request, such as a plan: what it is about.
207 #[serde(default)]
208 pub title: Option<String>,
209 pub kind: RunKind,
210 #[serde(default)]
211 pub agent: Option<String>,
212 #[serde(default)]
213 pub model: Option<String>,
214 /// The sandbox's name, which stopping it needs.
215 pub sandbox: String,
216 #[serde(default)]
217 pub started_by: Option<String>,
218 /// Its cost cap, from its guardrails, in US dollars.
219 #[serde(default)]
220 pub budget_usd: Option<f64>,
221 /// Its time cap, from its guardrails, in minutes.
222 #[serde(default)]
223 pub time_cap_minutes: Option<u32>,
224}
225
226/// `report_run`: a sandbox telling how its run goes, with the run's token.
227/// Steps are added, the current step replaced, and an outcome ends the run.
228/// A finished run accepts nothing more. Returns `Outcome<RunStatus>`: the
229/// run's status after the report, so a sandbox can tell it was stopped.
230#[derive(Debug, Default, Serialize, Deserialize)]
231#[serde(rename_all = "camelCase", default)]
232pub struct ReportRunArgs {
233 pub run_id: String,
234 pub token: String,
235 pub steps: Vec<String>,
236 pub step: Option<String>,
237 pub cost_usd: Option<f64>,
238 pub turns: Option<u32>,
239 /// `succeeded` or `failed`, to end the run.
240 pub outcome: Option<RunStatus>,
241 pub error: Option<String>,
242 /// `budget` or `time`: the run reached a cap of its guardrails and
243 /// stopped. Ends it as stopped, like a person's stop.
244 pub halt: Option<crate::guardrails::Halt>,
245}
246
247/// `stop_run`: a member stops a run. Marks it stopped and returns where its
248/// sandbox is, for the runner to destroy. A pull request it worked on waits
249/// for a person. Returns `Outcome<StoppedRun>`.
250#[derive(Debug, Serialize, Deserialize)]
251pub struct StopRunArgs {
252 pub actor: User,
253 pub repo: RepoPath,
254 pub id: String,
255}
256
257#[derive(Debug, Serialize, Deserialize)]
258#[serde(rename_all = "camelCase")]
259pub struct StoppedRun {
260 pub run: AgentRun,
261 pub sandbox: String,
262}
263
264/// `list_runs`: runs in a repository, or with `workspace` instead, in every
265/// repository of a workspace (members only), newest first. Returns
266/// `Outcome<Vec<AgentRun>>`.
267#[derive(Debug, Default, Serialize, Deserialize)]
268#[serde(rename_all = "camelCase", default)]
269pub struct ListRunsArgs {
270 pub viewer: Viewer,
271 pub repo: Option<RepoPath>,
272 pub workspace: Option<String>,
273 /// Only those queued or running.
274 pub active: bool,
275 pub kind: Option<RunKind>,
276 pub status: Option<RunStatus>,
277 /// Only those on this pull request.
278 pub number: Option<u32>,
279 /// At most 200; 50 if not given.
280 pub limit: Option<u32>,
281}
282
283/// `get_run`: one run with all its steps. Returns `Outcome<AgentRun>`.
284#[derive(Debug, Serialize, Deserialize)]
285pub struct GetRunArgs {
286 pub viewer: Viewer,
287 pub repo: RepoPath,
288 pub id: String,
289}
290
291/// A pull request's recorded session, summed up for a list.
292#[derive(Clone, Debug, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct SessionSummary {
295 pub number: u32,
296 pub title: String,
297 pub status: PullStatus,
298 /// The agent label on the pull request, such as `g1t-agent`.
299 pub agent: String,
300 pub entries: u32,
301 /// How many tools it called.
302 pub tools: u32,
303 /// The start of the first prompt.
304 pub prompt: Option<String>,
305 /// The kinds of the runs g1t made for it.
306 pub kinds: Vec<RunKind>,
307 pub runs: u32,
308 /// What its runs cost together. Members only.
309 pub cost_usd: Option<f64>,
310 /// Whether one of its runs is under way.
311 pub active: bool,
312 /// RFC 3339.
313 pub started_at: String,
314 pub last_at: String,
315}
316
317/// `list_sessions`: the pull requests of a repository that have a session,
318/// most recently active first. Returns `Outcome<Vec<SessionSummary>>`.
319#[derive(Debug, Default, Serialize, Deserialize)]
320#[serde(rename_all = "camelCase", default)]
321pub struct ListSessionsArgs {
322 pub viewer: Viewer,
323 pub repo: Option<RepoPath>,
324 /// Only those with a run of this kind.
325 pub kind: Option<RunKind>,
326 /// The pull request's status: `draft`, `open`, `merged` or `closed`.
327 pub outcome: Option<PullStatus>,
328 pub number: Option<u32>,
329}
330
331/// `get_session`: one pull request's session in full, with its runs.
332/// Returns `Outcome<SessionView>`.
333#[derive(Debug, Serialize, Deserialize)]
334pub struct GetSessionArgs {
335 pub viewer: Viewer,
336 pub repo: RepoPath,
337 pub number: u32,
338}
339
340#[derive(Clone, Debug, Serialize, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct SessionView {
343 pub pull: Pull,
344 /// Oldest first; the first 2000.
345 pub entries: Vec<SessionEntry>,
346 /// Newest first, with their steps.
347 pub runs: Vec<AgentRun>,
348 /// Members only.
349 pub cost_usd: Option<f64>,
350}
351
352// --- Memory -----------------------------------------------------------------
353
354/// Whose memory: one project's, or the whole workspace's.
355#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
356#[serde(rename_all = "snake_case")]
357pub enum MemoryScope {
358 /// About one project's codebase.
359 Project,
360 /// True across the workspace's projects.
361 Workspace,
362}
363
364impl MemoryScope {
365 pub fn as_str(self) -> &'static str {
366 match self {
367 MemoryScope::Project => "project",
368 MemoryScope::Workspace => "workspace",
369 }
370 }
371}
372
373#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
374#[serde(rename_all = "snake_case")]
375pub enum MemoryKind {
376 /// How something is: "staging lives at staging.example.com".
377 #[default]
378 Fact,
379 /// How things are done here: "we use pnpm everywhere".
380 Convention,
381 /// Something chosen, and why: "we keep Postgres, not MySQL, for jsonb".
382 Decision,
383 /// A trap: "the tests need TZ=UTC or the date tests fail".
384 Gotcha,
385}
386
387impl MemoryKind {
388 pub fn as_str(self) -> &'static str {
389 match self {
390 MemoryKind::Fact => "fact",
391 MemoryKind::Convention => "convention",
392 MemoryKind::Decision => "decision",
393 MemoryKind::Gotcha => "gotcha",
394 }
395 }
396
397 pub fn parse(value: &str) -> Option<MemoryKind> {
398 [
399 MemoryKind::Fact,
400 MemoryKind::Convention,
401 MemoryKind::Decision,
402 MemoryKind::Gotcha,
403 ]
404 .into_iter()
405 .find(|kind| kind.as_str() == value)
406 }
407}
408
409/// Where a memory came from.
410#[derive(Clone, Debug, Default, Serialize, Deserialize)]
411#[serde(rename_all = "camelCase")]
412pub struct MemorySource {
413 /// `person`, `agent` or `run`.
414 pub kind: String,
415 /// The agent run that learned it.
416 #[serde(default)]
417 pub run_id: Option<String>,
418 /// The project and pull request it was learned on.
419 #[serde(default)]
420 pub repo: Option<RepoPath>,
421 #[serde(default)]
422 pub number: Option<u32>,
423 /// What it was captured from: `run:<id>`, `comment:<id>`,
424 /// `pull:<repo id>#<n>`, `doc:<repo id>:<path>`. See `crate::capture`.
425 #[serde(default)]
426 pub reference: Option<String>,
427 /// What it was learned from, quoted.
428 #[serde(default)]
429 pub evidence: Option<String>,
430}
431
432/// Whether agents are given a memory: `kept` ones are; a `candidate` waits
433/// for review (see `crate::capture`); a `dismissed` one is never suggested
434/// again from the same wording.
435#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(rename_all = "snake_case")]
437pub enum MemoryStatus {
438 Candidate,
439 #[default]
440 Kept,
441 Dismissed,
442}
443
444impl MemoryStatus {
445 pub fn as_str(self) -> &'static str {
446 match self {
447 MemoryStatus::Candidate => "candidate",
448 MemoryStatus::Kept => "kept",
449 MemoryStatus::Dismissed => "dismissed",
450 }
451 }
452
453 pub fn parse(value: &str) -> Option<MemoryStatus> {
454 [MemoryStatus::Candidate, MemoryStatus::Kept, MemoryStatus::Dismissed]
455 .into_iter()
456 .find(|status| status.as_str() == value)
457 }
458}
459
460#[derive(Clone, Debug, Serialize, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct Memory {
463 pub id: String,
464 pub scope: MemoryScope,
465 /// The workspace's slug.
466 pub workspace: String,
467 /// For a project's memory, the project's repository.
468 pub repo: Option<RepoPath>,
469 pub text: String,
470 pub kind: MemoryKind,
471 pub source: MemorySource,
472 /// Who wrote it: a username, or `g1t-agent`.
473 pub created_by: String,
474 /// Pinned memories are given to every agent first.
475 pub pinned: bool,
476 /// RFC 3339.
477 pub created_at: String,
478 pub updated_at: String,
479 /// When it was last given to an agent.
480 pub last_used_at: Option<String>,
481 /// Kept memories are given to agents; candidates wait for review.
482 #[serde(default)]
483 pub status: MemoryStatus,
484 /// 0 to 1: how sure its source was. None for what people wrote.
485 #[serde(default)]
486 pub confidence: Option<f64>,
487 /// How many independent sources said it.
488 #[serde(default)]
489 pub seen: u32,
490}
491
492#[derive(Clone, Debug, Default, Serialize, Deserialize)]
493#[serde(rename_all = "camelCase")]
494pub struct Memories {
495 /// The project's own; empty when no project was named.
496 pub project: Vec<Memory>,
497 pub workspace: Vec<Memory>,
498}
499
500/// `list_memories`: a workspace's memory and, with `repo`, that project's.
501/// Members only. Returns `Outcome<Memories>`.
502#[derive(Debug, Serialize, Deserialize)]
503pub struct ListMemoriesArgs {
504 pub viewer: Viewer,
505 pub workspace: String,
506 #[serde(default)]
507 pub repo: Option<RepoPath>,
508}
509
510/// `add_memory`: a member or an agent adds to memory. A project's memory
511/// needs `repo`. Text that looks like a key or a token is refused.
512/// Returns `Outcome<Memory>`.
513#[derive(Debug, Serialize, Deserialize)]
514#[serde(rename_all = "camelCase")]
515pub struct AddMemoryArgs {
516 pub actor: User,
517 pub workspace: String,
518 #[serde(default)]
519 pub repo: Option<RepoPath>,
520 pub scope: MemoryScope,
521 pub text: String,
522 #[serde(default)]
523 pub kind: MemoryKind,
524 #[serde(default)]
525 pub pinned: bool,
526 /// For an agent: the pull request it is working on.
527 #[serde(default)]
528 pub from_number: Option<u32>,
529}
530
531/// `update_memory`: changes a memory's text, kind or pin. Members only.
532/// Returns `Outcome<Memory>`.
533#[derive(Debug, Serialize, Deserialize)]
534pub struct UpdateMemoryArgs {
535 pub actor: User,
536 pub workspace: String,
537 pub id: String,
538 #[serde(default)]
539 pub text: Option<String>,
540 #[serde(default)]
541 pub kind: Option<MemoryKind>,
542 #[serde(default)]
543 pub pinned: Option<bool>,
544}
545
546/// `delete_memory`: forgets a memory. Members only. Returns `Outcome<bool>`.
547#[derive(Debug, Serialize, Deserialize)]
548pub struct DeleteMemoryArgs {
549 pub actor: User,
550 pub workspace: String,
551 pub id: String,
552}
553
554/// `recall`: what a project and its workspace remember, matching `query`
555/// when given (every word, in any order), pinned first. Members and g1t's
556/// agents. Returns `Outcome<Memories>`.
557#[derive(Debug, Serialize, Deserialize)]
558pub struct RecallArgs {
559 pub viewer: Viewer,
560 pub repo: RepoPath,
561 #[serde(default)]
562 pub query: Option<String>,
563 #[serde(default)]
564 pub limit: Option<u32>,
565}
566
567/// `memory_context`: what to tell an agent starting work in `repo`, within
568/// `budget` characters: pinned first, then the most recently used, the
569/// workspace's and the project's labelled apart. Marks what it gives as
570/// used. Called by the runner service only. Returns `MemoryContext`.
571#[derive(Debug, Serialize, Deserialize)]
572pub struct MemoryContextArgs {
573 pub repo: RepoPath,
574 #[serde(default)]
575 pub budget: Option<u32>,
576}
577
578#[derive(Clone, Debug, Default, Serialize, Deserialize)]
579pub struct MemoryContext {
580 /// None when there is nothing to tell.
581 pub text: Option<String>,
582 pub count: u32,
583}
584
585/// The longest a memory may be.
586pub const MAX_MEMORY_CHARS: usize = 1000;
587
588/// Prefixes of credentials that say what they are.
589const SECRET_PREFIXES: [(&str, &str); 20] = [
590 ("sk-ant-", "an Anthropic key"),
591 ("sk-proj-", "an OpenAI key"),
592 ("sk_live_", "a Stripe key"),
593 ("sk_test_", "a Stripe key"),
594 ("rk_live_", "a Stripe key"),
595 ("whsec_", "a webhook signing secret"),
596 ("ghp_", "a GitHub token"),
597 ("gho_", "a GitHub token"),
598 ("ghs_", "a GitHub token"),
599 ("ghu_", "a GitHub token"),
600 ("github_pat_", "a GitHub token"),
601 ("glpat-", "a GitLab token"),
602 ("xoxb-", "a Slack token"),
603 ("xoxp-", "a Slack token"),
604 ("AKIA", "an AWS access key"),
605 ("ASIA", "an AWS access key"),
606 ("AIza", "a Google API key"),
607 ("g1t_", "a g1t token"),
608 ("npm_", "an npm token"),
609 ("SG.", "a SendGrid key"),
610];
611
612/// Words that, followed by `=` or `:` and a value, set a credential.
613const SECRET_WORDS: [&str; 8] = [
614 "password",
615 "passwd",
616 "secret",
617 "api_key",
618 "apikey",
619 "api-key",
620 "token",
621 "private_key",
622];
623
624/// Bits of entropy per character of `word`.
625fn entropy(word: &str) -> f64 {
626 let mut counts = std::collections::HashMap::new();
627 for c in word.chars() {
628 *counts.entry(c).or_insert(0usize) += 1;
629 }
630 let length = word.chars().count() as f64;
631 counts
632 .values()
633 .map(|&count| {
634 let p = count as f64 / length;
635 -p * p.log2()
636 })
637 .sum()
638}
639
640/// What `text` seems to hold that must never be stored in memory, which
641/// every agent in the workspace reads: a key, a token, a private key or a
642/// password. None when it looks clean. Errs on the side of refusing; a
643/// person can always say where a secret lives instead of what it is.
644pub fn secret_in(text: &str) -> Option<&'static str> {
645 if text.contains("-----BEGIN") && text.contains("PRIVATE KEY") {
646 return Some("a private key");
647 }
648 let lower = text.to_lowercase();
649 for word in SECRET_WORDS {
650 let mut rest = lower.as_str();
651 while let Some(at) = rest.find(word) {
652 let after = rest[at + word.len()..].trim_start_matches(['"', '\'', ' ']);
653 if let Some(value) = after.strip_prefix(['=', ':']) {
654 let value: String = value
655 .trim_start_matches([' ', '"', '\''])
656 .chars()
657 .take_while(|c| !c.is_whitespace() && *c != '"' && *c != '\'' && *c != ',')
658 .collect();
659 // "token: see 1Password" names where it is, which is fine.
660 if value.chars().count() >= 8 && value.chars().any(|c| c.is_ascii_digit()) {
661 return Some("a password or token");
662 }
663 }
664 rest = &rest[at + word.len()..];
665 }
666 }
667 let words = text.split(|c: char| {
668 c.is_whitespace() || matches!(c, '"' | '\'' | '`' | ',' | ';' | '(' | ')' | '<' | '>' | '[' | ']' | '{' | '}')
669 });
670 for word in words {
671 let word = word.trim_end_matches(['.', ':']);
672 // A key=value pair is judged by its value.
673 let word = word.rsplit_once('=').map_or(word, |(_, value)| value);
674 for (prefix, what) in SECRET_PREFIXES {
675 if let Some(rest) = word.strip_prefix(prefix) {
676 let tail = rest.chars().filter(|c| c.is_ascii_alphanumeric()).count();
677 if tail >= 12 {
678 return Some(what);
679 }
680 }
681 }
682 // A URL with a password in it.
683 if let Some((_, rest)) = word.split_once("://")
684 && let Some((credentials, _)) = rest.split_once('@')
685 && credentials.contains(':')
686 {
687 return Some("a URL with a password in it");
688 }
689 let length = word.chars().count();
690 if length < 32 || word.contains("://") || word.contains('/') && !word.contains('+') {
691 continue;
692 }
693 let token_chars = word
694 .chars()
695 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+' | '/' | '='));
696 if !token_chars {
697 continue;
698 }
699 let hex = word.chars().all(|c| c.is_ascii_hexdigit());
700 // A commit's id is 40 hex characters and fine; longer runs of hex
701 // are keys and digests of keys.
702 if hex {
703 if length >= 48 {
704 return Some("a key or token");
705 }
706 continue;
707 }
708 let upper = word.chars().any(|c| c.is_ascii_uppercase());
709 let lower = word.chars().any(|c| c.is_ascii_lowercase());
710 let digit = word.chars().any(|c| c.is_ascii_digit());
711 if upper && lower && digit && entropy(word) > 4.0 {
712 return Some("a key or token");
713 }
714 }
715 None
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721
722 #[test]
723 fn plain_knowledge_is_kept() {
724 for text in [
725 "We use pnpm everywhere, never npm or yarn.",
726 "Staging lives at https://staging.example.com and deploys from main.",
727 "The tests need TZ=UTC or the date tests fail.",
728 "Commit 9f2c4e1a7b3d5f60812a4c6e8b0d2f4a6c8e0b13 introduced the flaky retry.",
729 "The API token is in 1Password under 'Deploy'.",
730 "token: ask Ana for one",
731 "src/components/ui/select.tsx wraps Radix; import from there, not radix-ui.",
732 "Run cargo test -p g1t-work before pushing changes to services/work.",
733 ] {
734 assert_eq!(secret_in(text), None, "{text}");
735 }
736 }
737
738 #[test]
739 fn credentials_are_refused() {
740 // Key-shaped values are joined at run time: no whole key sits in the
741 // source for secret scanners to flag.
742 let join = |a: &str, b: &str| format!("{a}{b}");
743 for text in [
744 join("The key is sk-", "ant-api03-abcdefghijklmnopqrstuvwxyz"),
745 join("use gh", "p_abcdefghijklmnopqrstuvwxyz0123456789 to clone"),
746 join("AWS: AK", "IAIOSFODNN7EXAMPLE"),
747 join("STRIPE_KEY=sk_l", "ive_51HabcdefghijklmnopQRSTUV"),
748 "password = hunter2hunter2".to_owned(),
749 "db: postgres://admin:s3cret@db.internal:5432/app".to_owned(),
750 "token is 3f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a".to_owned(),
751 "-----BEGIN RSA PRIVATE KEY-----\nMIIE...".to_owned(),
752 "secret: Zq8wN3vR7tY2uI5oP1aS6dF4gH9jK0lX".to_owned(),
753 "it is xK9mQ2vL8nR4tP7wZ3yB6cF1dG5hJ0sA".to_owned(),
754 ] {
755 assert!(secret_in(&text).is_some(), "{text}");
756 }
757 }
758
759 #[test]
760 fn kinds_and_statuses_round_trip() {
761 for kind in RunKind::ALL {
762 assert_eq!(RunKind::parse(kind.as_str()), Some(kind));
763 }
764 assert!(RunKind::Implement.takes_messages() && !RunKind::Review.takes_messages());
765 assert!(!RunKind::Checks.is_agent());
766 assert_eq!(RunStatus::parse("stopped"), Some(RunStatus::Stopped));
767 assert!(RunStatus::Queued.is_active() && !RunStatus::Failed.is_active());
768 assert_eq!(MemoryKind::parse("gotcha"), Some(MemoryKind::Gotcha));
769 }
770}