Skip to content
1,250 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1//! Run credentials: the least-privilege tokens a sandbox works with.
2//!
3//! Every sandbox run gets its own tokens, bound to the run, its repository
4//! (and the pull request's fork), what that kind of run needs to do, and an
5//! expiry no later than the run's timeout. Each carries a composite
6//! identity: an agent acting on behalf of the person who started the work.
7//! What it may do is the intersection of the two: the run's scope, and what
8//! that person may do right now.
9//!
10//! The policy lives here, as pure functions, so that identity (which mints
11//! the tokens), the API (which serves REST and MCP) and repos (which serves
12//! git) all enforce the same rules, and so the rules can be tested.
13
14use serde::{Deserialize, Serialize};
15
16use crate::identity::AgentScope;
17use crate::repos::RepoPath;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look18use crate::access::{BasePermission, RepoGrant, RepoRole};
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API19use crate::{Membership, PrincipalKind, Role, User};
20
21/// What a run does, as far as its credentials are concerned. The same names
22/// as [`crate::agents::RunKind`], plus `deploy`, a build of one commit.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum RunCredentialKind {
26 Implement,
27 Revise,
28 Review,
29 Answer,
30 Update,
31 Plan,
32 Checks,
33 Queue,
34 Mergecheck,
35 Deploy,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily36 /// A security update: raising one package's version in its lockfiles
37 /// and pushing that to a branch of its own. Not an agent.
38 Bump,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API39}
40
41impl RunCredentialKind {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily42 pub const ALL: [RunCredentialKind; 11] = [
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API43 RunCredentialKind::Implement,
44 RunCredentialKind::Revise,
45 RunCredentialKind::Review,
46 RunCredentialKind::Answer,
47 RunCredentialKind::Update,
48 RunCredentialKind::Plan,
49 RunCredentialKind::Checks,
50 RunCredentialKind::Queue,
51 RunCredentialKind::Mergecheck,
52 RunCredentialKind::Deploy,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily53 RunCredentialKind::Bump,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API54 ];
55
56 pub fn as_str(self) -> &'static str {
57 match self {
58 RunCredentialKind::Implement => "implement",
59 RunCredentialKind::Revise => "revise",
60 RunCredentialKind::Review => "review",
61 RunCredentialKind::Answer => "answer",
62 RunCredentialKind::Update => "update",
63 RunCredentialKind::Plan => "plan",
64 RunCredentialKind::Checks => "checks",
65 RunCredentialKind::Queue => "queue",
66 RunCredentialKind::Mergecheck => "mergecheck",
67 RunCredentialKind::Deploy => "deploy",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily68 RunCredentialKind::Bump => "bump",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API69 }
70 }
71
72 /// Whether the run works on one pull request, whose session and
73 /// readiness it reports.
74 fn works_on_a_pull(self) -> bool {
75 matches!(
76 self,
77 RunCredentialKind::Implement
78 | RunCredentialKind::Revise
79 | RunCredentialKind::Answer
80 | RunCredentialKind::Update
81 )
82 }
83}
84
85/// Which part of a sandbox a credential is for.
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum CredentialUse {
89 /// g1t's runner: cloning, pushing the result, recording the session.
90 /// It acts as the person downstream, so that what it pushes and records
91 /// is theirs, within the run's scope.
92 Runner,
93 /// The agent's own tools, over MCP. It acts as the agent.
94 Tools,
95}
96
97impl CredentialUse {
98 pub fn as_str(self) -> &'static str {
99 match self {
100 CredentialUse::Runner => "runner",
101 CredentialUse::Tools => "tools",
102 }
103 }
104}
105
106/// A repository a run may push to, and the one branch, if only one.
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
108pub struct GitGrant {
109 pub repo: RepoPath,
110 /// Null: any branch. A pull request's fork is its own repository, so
111 /// the whole of it is the pull request's.
112 #[serde(default)]
113 pub branch: Option<String>,
114}
115
116/// What binds an agent's token to one run. Absent on agent tokens made
117/// before run credentials, which keep working for the API only.
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct RunBinding {
121 pub kind: RunCredentialKind,
122 #[serde(rename = "use")]
123 pub usage: CredentialUse,
124 /// The agent run, once the sandbox has recorded it.
125 #[serde(default)]
126 pub run_id: Option<String>,
127 /// The pull request the run works on, for the kinds that work on one.
128 #[serde(default)]
129 pub number: Option<u32>,
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent130 /// The agent's name, such as `g1t`.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API131 pub agent: String,
132 /// Repositories it may clone and fetch, besides those it may push to.
133 #[serde(default)]
134 pub read: Vec<RepoPath>,
135 /// Where it may push.
136 #[serde(default)]
137 pub push: Vec<GitGrant>,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily138 /// g1t's own run (a security update, an agent g1t put on one): the
139 /// credential belongs to the workspace, and acts on behalf of g1t
140 /// (`system::ID`), so what it does is g1t's, and the pull request g1t
141 /// opened, and its working copy, are its own.
142 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143 pub system: bool,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API144}
145
146/// A person, by id and name.
147#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Principal {
149 pub id: String,
150 pub username: String,
151}
152
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights153impl From<&User> for Principal {
154 fn from(user: &User) -> Self {
155 Principal {
156 id: user.id.clone(),
157 username: user.username.clone(),
158 }
159 }
160}
161
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API162/// Set on a [`User`] resolved from an agent's token: the composite
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent163/// identity, "g1t on behalf of syntaqx", and what it may do.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API164#[derive(Clone, Debug, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct Acting {
167 /// The token's id, as audit entries name it.
168 pub credential_id: String,
169 pub agent: String,
170 pub on_behalf_of: Principal,
171 pub scope: AgentScope,
172}
173
174impl Acting {
175 pub fn run(&self) -> Option<&RunBinding> {
176 self.scope.run.as_ref()
177 }
178}
179
180/// `create_run_credential`: a token for one sandbox run. It acts as
181/// `agent` on behalf of `on_behalf_of`, can do only what `kind` and `usage`
182/// allow in `repo`, and expires after `ttl_seconds`, which should be the
183/// run's timeout. Returns `CreatedAccessToken`.
184#[derive(Clone, Debug, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct CreateRunCredentialArgs {
187 pub on_behalf_of: User,
188 pub repo: RepoPath,
189 pub kind: RunCredentialKind,
190 #[serde(rename = "use")]
191 pub usage: CredentialUse,
192 #[serde(default)]
193 pub number: Option<u32>,
194 #[serde(default)]
195 pub read: Vec<RepoPath>,
196 #[serde(default)]
197 pub push: Vec<GitGrant>,
198 pub ttl_seconds: u64,
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent199 /// Defaults to `g1t`.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API200 #[serde(default)]
201 pub agent: Option<String>,
202}
203
204/// `bind_run_credentials`: ties tokens, named by the SHA-256 of their
205/// text in hex, to the agent run their sandbox recorded. Returns how many.
206#[derive(Clone, Debug, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct BindRunCredentialsArgs {
209 pub token_hashes: Vec<String>,
210 pub run_id: String,
211}
212
213/// `revoke_run_credentials`: ends tokens when their sandbox stops, by hash
214/// or by run. Only run credentials are touched, never a token a person
215/// made. Returns how many.
216#[derive(Clone, Debug, Default, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct RevokeRunCredentialsArgs {
219 #[serde(default)]
220 pub token_hashes: Vec<String>,
221 #[serde(default)]
222 pub run_id: Option<String>,
223}
224
225// --- Policy --------------------------------------------------------------
226
227/// Operations that only read.
228pub const READ_OPERATIONS: &[&str] = &[
229 "whoami",
Usage, Billing settings and prepaid AI credit; fixes from the UX audit230 "get_usage",
231 "get_budget",
232 "get_ai_credit",
233 "list_invoices",
234 "get_billing_details",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API235 "list_repos",
236 "get_repo",
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97237 "list_projects",
238 "get_project",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look239 "list_deleted_repos",
240 "list_collaborators",
241 "get_collaborator_permission",
242 "list_repo_invitations",
243 "list_my_repo_invitations",
244 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar245 "list_teams",
246 "get_team",
247 "list_team_members",
248 "list_child_teams",
249 "list_team_repos",
250 "list_user_teams",
251 "get_codeowners_errors",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API252 "get_repo_settings",
Fast pages, required checks on the branch, self-hosted runners, honest incidents253 "list_check_names",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API254 "get_merge_queue",
255 "recall",
256 "list_issues",
257 "get_issue",
258 "get_plan",
259 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar260 "list_issue_labels",
261 "list_milestones",
262 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API263 "list_pull_requests",
264 "get_pull_request",
265 "read_session",
266 "get_pull_request_changes",
267 "list_events",
268 "get_context",
269 "search_context",
270 "get_entity",
Search across all of g1t, Explore, and a command palette271 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API272 "list_workflows",
273 "list_workflow_runs",
274 "get_workflow_run",
275 "get_job_logs",
276 "list_integrations",
277 "get_model_routes",
278 "list_webhooks",
279 "list_webhook_deliveries",
280 "list_actions_secrets",
281 "list_actions_variables",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily282 "list_security_alerts",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar283 "list_secret_scanning_alerts",
284 "get_secret_scanning_alert",
285 "list_secret_scanning_locations",
286 "list_bypass_requests",
287 "list_custom_patterns",
288 "list_code_scanning_alerts",
289 "get_code_scanning_alert",
290 "list_code_scanning_analyses",
291 "get_sarif_upload",
292 "list_vulnerability_alerts",
293 "get_vulnerability_alert",
294 "get_dependency_graph",
295 "get_sbom",
296 "compare_dependencies",
297 "get_security_settings",
298 "get_workspace_security_settings",
299 "get_security_overview",
API: notifications over REST and MCP, with notifications scopes300 "list_notifications",
301 "get_notification_thread",
302 "get_thread_subscription",
303 "get_repo_subscription",
304 "list_watched_repos",
API: pinned projects over REST and MCP305 "list_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API306];
307
308/// What no agent's token may ever do, whatever its scope says: workspaces,
309/// repositories' settings, members, tokens, billing, integrations,
310/// webhooks, secrets, workflows' controls, merging, and putting more agents
311/// to work.
312pub const NEVER: &[&str] = &[
Usage, Billing settings and prepaid AI credit; fixes from the UX audit313 // Billing is people's: agents never spend or change it.
314 "set_budget",
315 "buy_ai_credit",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API316 "create_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look317 "delete_workspace",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily318 "update_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look319 "transfer_repo",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API320 "create_repo",
321 "update_repo",
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97322 "update_project",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look323 "delete_repo",
324 "list_deleted_repos",
325 "restore_repo",
326 "purge_repo",
327 "rename_repo",
328 "archive_repo",
329 "unarchive_repo",
330 "set_repo_visibility",
331 "rename_branch",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API332 "update_repo_settings",
333 "merge_pull_request",
334 "assign_issue",
335 "plan_work",
336 "apply_plan",
337 "import_issue",
338 "list_integrations",
339 "connect_integration",
AI Gateway: OpenAI's format, open models, and your own providers340 "update_integration",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API341 "disconnect_integration",
342 "test_integration",
343 "get_model_routes",
344 "set_model_routes",
345 "list_webhooks",
346 "create_webhook",
347 "update_webhook",
348 "delete_webhook",
349 "ping_webhook",
350 "list_webhook_deliveries",
351 "redeliver_webhook",
352 "dispatch_workflow",
353 "cancel_workflow_run",
354 "rerun_workflow_run",
355 "update_workflow",
356 "list_actions_secrets",
357 "set_actions_secret",
358 "delete_actions_secret",
359 "list_actions_variables",
360 "set_actions_variable",
361 "delete_actions_variable",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look362 "list_collaborators",
363 "get_collaborator_permission",
364 "add_collaborator",
365 "update_collaborator",
366 "remove_collaborator",
367 "list_repo_invitations",
368 "revoke_repo_invitation",
369 "list_my_repo_invitations",
370 "accept_repo_invitation",
371 "decline_repo_invitation",
372 "set_base_permission",
373 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar374 // Teams: who is in which, and what they reach, is for people.
375 "create_team",
376 "update_team",
377 "delete_team",
378 "set_team_member",
379 "remove_team_member",
380 "set_team_repo",
381 "remove_team_repo",
382 "set_team_review_assignment",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily383 // Dismissing a secret lets it through push protection.
384 "dismiss_security_alert",
385 "reopen_security_alert",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar386 // Nor any other decision about security: closing or reopening an
387 // alert, pushing past push protection or deciding who may, changing
388 // what is looked for or when checks fail, or putting more agents to
389 // work. An agent fixes what it finds in its own pull request.
390 "update_secret_scanning_alert",
391 "bypass_push_protection",
392 "review_bypass_request",
393 "create_custom_pattern",
394 "update_custom_pattern",
395 "delete_custom_pattern",
396 "update_code_scanning_alert",
397 "update_vulnerability_alert",
398 "fix_security_alert",
399 "update_security_settings",
400 "update_workspace_security_settings",
API: notifications over REST and MCP, with notifications scopes401 // A person's own inbox: g1t's agents act as g1t, which has none.
402 "list_notifications",
403 "get_notification_thread",
404 "mark_notifications_read",
405 "mark_thread_read",
406 "mark_thread_done",
407 "save_thread",
408 "snooze_thread",
409 "get_thread_subscription",
410 "set_thread_subscription",
411 "delete_thread_subscription",
412 "get_repo_subscription",
413 "set_repo_subscription",
414 "delete_repo_subscription",
415 "list_watched_repos",
API: pinned projects over REST and MCP416 // Pins are a person's own, as the inbox is.
417 "list_pinned_projects",
418 "pin_project",
419 "unpin_project",
420 "reorder_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API421];
422
423/// Reading what an agent needs to know about its repository.
424const TOOLS_READ: &[&str] = &[
425 "get_repo",
426 "list_issues",
427 "get_issue",
428 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar429 "list_issue_labels",
430 "list_milestones",
431 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API432 "list_pull_requests",
433 "get_pull_request",
434 "get_pull_request_changes",
435 "read_session",
436 "get_merge_queue",
437 "list_events",
438 "recall",
439 "search_context",
440 "get_entity",
Search across all of g1t, Explore, and a command palette441 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API442 "list_workflows",
443 "list_workflow_runs",
444 "get_workflow_run",
445 "get_job_logs",
446];
447
448pub fn is_read(operation: &str) -> bool {
449 READ_OPERATIONS.contains(&operation)
450}
451
452/// The API and MCP operations a run of `kind` may use with a credential
453/// for `usage`. Git is separate: see [`decide_git`].
454pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
455 use RunCredentialKind as K;
456 let mut operations: Vec<&'static str> = Vec::new();
457 match usage {
458 CredentialUse::Runner => {
459 if kind.works_on_a_pull() {
460 operations.extend(["get_repo", "get_pull_request", "record_session"]);
461 }
462 if kind == K::Implement {
463 operations.push("mark_pull_request_ready");
464 }
465 }
466 CredentialUse::Tools => match kind {
467 K::Implement | K::Revise | K::Answer => {
468 operations.extend(TOOLS_READ.iter().copied());
469 operations.extend([
470 "create_issue",
471 "add_comment",
472 "take_messages",
473 "remember",
474 "message_agent",
475 "answer_message",
476 "get_context",
477 ]);
478 }
479 K::Review => {
480 operations.extend(TOOLS_READ.iter().copied());
481 operations.extend(["add_comment", "review_pull_request", "get_context"]);
482 }
483 K::Plan => {
484 operations.extend(TOOLS_READ.iter().copied());
485 operations.extend(["create_issue", "get_context"]);
486 }
487 K::Update => operations.extend(TOOLS_READ.iter().copied()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily488 K::Checks | K::Queue | K::Mergecheck | K::Deploy | K::Bump => {}
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API489 },
490 }
491 operations
492}
493
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step494/// What a run's credential may do, in the scope vocabulary that access
495/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
496/// for a runner, git's. Its operations, its repository and its run still
497/// bound it more tightly than these scopes say.
498pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
499 use crate::scopes::{Scope, normalize, scope_for};
500 let mut scopes: Vec<Scope> = operations_for(kind, usage)
501 .into_iter()
502 .filter_map(scope_for)
503 .collect();
504 if usage == CredentialUse::Runner {
505 scopes.push(Scope::CodeRead);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily506 if matches!(
507 kind,
508 RunCredentialKind::Implement
509 | RunCredentialKind::Revise
510 | RunCredentialKind::Answer
511 | RunCredentialKind::Update
512 | RunCredentialKind::Bump
513 ) {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step514 scopes.push(Scope::CodeWrite);
515 }
516 }
517 normalize(&mut scopes);
518 scopes
519}
520
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API521/// Operations that change a pull request, which a runner may do only to
522/// the pull request its run works on.
523const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
524
525/// Whether something was allowed, and the rule that decided it.
526#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
527pub struct Decision {
528 pub allowed: bool,
529 /// A short, stable name: `run:implement/tools`, `never`,
530 /// `scope:repository` and so on. Shown in the audit log.
531 pub rule: String,
532 /// Why it was refused, for the caller.
533 #[serde(default, skip_serializing_if = "Option::is_none")]
534 pub reason: Option<String>,
535}
536
537impl Decision {
538 pub fn allow(rule: impl Into<String>) -> Self {
539 Decision {
540 allowed: true,
541 rule: rule.into(),
542 reason: None,
543 }
544 }
545
546 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
547 Decision {
548 allowed: false,
549 rule: rule.into(),
550 reason: Some(reason.into()),
551 }
552 }
553}
554
555fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
556 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
557}
558
559fn scope_rule(scope: &AgentScope) -> String {
560 match &scope.run {
561 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
562 None => "agent-token".to_owned(),
563 }
564}
565
566/// Whether `user`, resolved from an agent's token with `scope`, may use
567/// `operation`. `repo` is the repository the call names, if any, and
568/// `needs_repo` whether the operation is about one; `number` the issue or
569/// pull request it names.
570pub fn decide_operation(
571 user: &User,
572 scope: &AgentScope,
573 operation: &str,
574 repo: Option<&RepoPath>,
575 needs_repo: bool,
576 number: Option<u32>,
577) -> Decision {
578 let who = "A g1t agent's token";
579 if NEVER.contains(&operation) {
580 return Decision::deny(
581 "never",
582 format!(
583 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
584 ),
585 );
586 }
587 if !scope.operations.iter().any(|name| name == operation) {
588 return Decision::deny(
589 "scope:operation",
590 format!("{who} for this run cannot use {operation}."),
591 );
592 }
593 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
594 return Decision::deny(
595 "scope:repository",
596 format!(
597 "{who} works in {}/{} only.",
598 scope.repo.namespace, scope.repo.name
599 ),
600 );
601 }
602 // The intersection: the person it acts for must still be able to work
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look603 // in the repository's workspace, as a member or with a role on its
604 // repositories. What it may do in the repository itself is their
605 // role there, which services check (`access::can`).
606 if !crate::access::has_access_in(user, &scope.repo.namespace) {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API607 return Decision::deny(
608 "on-behalf-of:membership",
609 format!(
610 "The person this agent works for is no longer a member of {}.",
611 scope.repo.namespace
612 ),
613 );
614 }
615 if let Some(run) = &scope.run
616 && run.usage == CredentialUse::Runner
617 && PULL_WRITES.contains(&operation)
618 && run.number.is_some()
619 && number != run.number
620 {
621 return Decision::deny(
622 "scope:pull",
623 format!(
624 "{who} can change pull request #{} only.",
625 run.number.unwrap_or_default()
626 ),
627 );
628 }
629 Decision::allow(scope_rule(scope))
630}
631
632/// Whether a run credential may clone or fetch (`write` false), or push to
633/// (`write` true), the repository at `repo`.
634pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
635 let Some(run) = scope
636 .run
637 .as_ref()
638 .filter(|run| run.usage == CredentialUse::Runner)
639 else {
640 return Decision::deny(
641 "git:not-a-run",
642 "A g1t agent's tools token cannot be used with git.",
643 );
644 };
645 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
646 if write {
647 return if pushable {
648 Decision::allow(format!("{}:push", scope_rule(scope)))
649 } else {
650 Decision::deny(
651 "git:push",
652 format!(
653 "A {} run cannot push to {}/{}.",
654 run.kind.as_str(),
655 repo.namespace,
656 repo.name
657 ),
658 )
659 };
660 }
661 let readable = pushable
662 || same_repo(&scope.repo, repo)
663 || run.read.iter().any(|path| same_repo(path, repo));
664 if readable {
665 Decision::allow(format!("{}:read", scope_rule(scope)))
666 } else {
667 Decision::deny(
668 "git:read",
669 format!(
670 "A {} run cannot read {}/{}.",
671 run.kind.as_str(),
672 repo.namespace,
673 repo.name
674 ),
675 )
676 }
677}
678
679/// Whether a push to `repo` is limited to certain branches, so that the
680/// refs it moves have to be read and checked with [`decide_refs`].
681pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
682 scope
683 .run
684 .iter()
685 .flat_map(|run| run.push.iter())
686 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
687}
688
689/// Whether a push to `repo` may move `refs` (full refs, such as
690/// `refs/heads/main`). Tags are never a run's to move.
691pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
692 let repo_decision = decide_git(scope, repo, true);
693 if !repo_decision.allowed {
694 return repo_decision;
695 }
696 let grants: Vec<&GitGrant> = scope
697 .run
698 .iter()
699 .flat_map(|run| run.push.iter())
700 .filter(|grant| same_repo(&grant.repo, repo))
701 .collect();
702 for git_ref in refs {
703 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
704 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
705 };
706 let allowed = grants
707 .iter()
708 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
709 if !allowed {
710 return Decision::deny(
711 "git:ref",
712 format!(
713 "A run cannot push to {branch} in {}/{}.",
714 repo.namespace, repo.name
715 ),
716 );
717 }
718 }
719 repo_decision
720}
721
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look722/// The most an agent may be on a repository, whoever it works for: it
723/// can push, merge and run, never change settings or who has access.
724pub const AGENT_CEILING: RepoRole = RepoRole::Write;
725
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API726/// The memberships an agent working for `person` has: the run's
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look727/// workspace, as a member, only if the person is in it now, with the
728/// person's role on its repositories (an owner's Admin included) cut down
729/// to [`AGENT_CEILING`].
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API730pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
731 let namespace = namespace.to_lowercase();
732 person
733 .iter()
734 .filter(|membership| membership.slug == namespace)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look735 .map(|membership| {
736 let base = match membership.role {
737 Role::Owner => BasePermission::Admin,
738 Role::Member => membership.base_permission.unwrap_or_default(),
739 };
740 Membership {
741 role: Role::Member,
742 base_permission: Some(match base {
743 BasePermission::Admin => BasePermission::Write,
744 base => base,
745 }),
746 ..membership.clone()
747 }
748 })
749 .collect()
750}
751
752/// The repository grants an agent working for `person` has: those in the
753/// run's workspace, each cut down to [`AGENT_CEILING`].
754pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
755 let namespace = namespace.to_lowercase();
756 person
757 .iter()
758 .filter(|grant| grant.workspace == namespace)
759 .map(|grant| RepoGrant {
760 role: grant.role.min(AGENT_CEILING),
761 ..grant.clone()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API762 })
763 .collect()
764}
765
766/// Who a runner's credential acts as downstream: the person, with only the
767/// agent's (already intersected) memberships. `None` for anything else.
768pub fn as_person(user: &User) -> Option<User> {
769 let acting = user.acting.as_ref()?;
770 if user.kind != PrincipalKind::Agent {
771 return None;
772 }
773 let run = acting.run()?;
774 if run.usage != CredentialUse::Runner {
775 return None;
776 }
777 Some(User {
778 id: acting.on_behalf_of.id.clone(),
779 username: acting.on_behalf_of.username.clone(),
780 kind: PrincipalKind::User,
781 verified: user.verified,
782 workspaces: user.workspaces.clone(),
783 avatar: None,
784 acting: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look785 grants: user.grants.clone(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step786 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API787 })
788}
789
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent790/// How an actor is described: "g1t on behalf of syntaqx".
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API791pub fn describe(user: &User) -> String {
792 match &user.acting {
793 Some(acting) => format!(
794 "{} on behalf of {}",
795 acting.agent, acting.on_behalf_of.username
796 ),
797 None => user.username.clone(),
798 }
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804
805 #[test]
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step806 fn a_run_s_scopes_are_never_admin() {
807 for kind in RunCredentialKind::ALL {
808 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
809 let scopes = run_scopes(kind, usage);
810 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
811 }
812 }
813 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
814 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
815 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
816 }
817
818 #[test]
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API819 fn agents_can_search_the_context_hub() {
820 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
821 let tools = operations_for(kind, CredentialUse::Tools);
822 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
823 }
824 assert!(is_read("search_context") && is_read("get_entity"));
825 }
826
Search across all of g1t, Explore, and a command palette827 #[test]
828 fn agents_can_search_all_of_g1t() {
829 // Site-wide search only reads: every run that reads its repository
830 // may use it, and nothing that never reads gets it.
831 assert!(is_read("search"));
832 assert!(!NEVER.contains(&"search"));
833 for kind in [
834 RunCredentialKind::Implement,
835 RunCredentialKind::Revise,
836 RunCredentialKind::Answer,
837 RunCredentialKind::Review,
838 RunCredentialKind::Plan,
839 RunCredentialKind::Update,
840 ] {
841 let tools = operations_for(kind, CredentialUse::Tools);
842 assert!(tools.contains(&"search"), "{kind:?} should search");
843 // The context hub's search stays its own tool beside it.
844 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
845 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily846 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
Search across all of g1t, Explore, and a command palette847 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
848 }
849 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
850 }
851
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API852 fn path(namespace: &str, name: &str) -> RepoPath {
853 RepoPath {
854 namespace: namespace.to_owned(),
855 name: name.to_owned(),
856 }
857 }
858
859 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
860 AgentScope {
861 repo: path("acme", "rocket"),
862 operations: operations_for(kind, usage)
863 .into_iter()
864 .map(str::to_owned)
865 .collect(),
866 run: Some(RunBinding {
867 kind,
868 usage,
869 run_id: Some("run_1".to_owned()),
870 number: Some(7),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent871 agent: "g1t".to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily872 system: false,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API873 read: vec![path("acme", "rocket")],
874 push: match kind {
875 RunCredentialKind::Implement
876 | RunCredentialKind::Revise
877 | RunCredentialKind::Answer => vec![GitGrant {
878 repo: path("pulls", "pul_7"),
879 branch: None,
880 }],
881 RunCredentialKind::Update => vec![GitGrant {
882 repo: path("acme", "rocket"),
883 branch: Some("fix-login".to_owned()),
884 }],
885 _ => vec![],
886 },
887 }),
888 }
889 }
890
891 fn agent(member_of: &[&str], scope: AgentScope) -> User {
892 User {
893 id: "usr_g1t_agent".to_owned(),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent894 username: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API895 kind: PrincipalKind::Agent,
896 verified: true,
897 workspaces: member_of
898 .iter()
899 .map(|slug| Membership::member(*slug))
900 .collect(),
901 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look902 grants: Vec::new(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step903 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API904 acting: Some(Box::new(Acting {
905 credential_id: "tok_1".to_owned(),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent906 agent: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API907 on_behalf_of: Principal {
908 id: "usr_1".to_owned(),
909 username: "syntaqx".to_owned(),
910 },
911 scope,
912 })),
913 }
914 }
915
916 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
917 let scope = scope(kind, usage);
918 let user = agent(&["acme"], scope.clone());
919 decide_operation(
920 &user,
921 &scope,
922 operation,
923 Some(&path("acme", "rocket")),
924 true,
925 Some(7),
926 )
927 }
928
929 use CredentialUse::{Runner, Tools};
930 use RunCredentialKind as K;
931
932 /// Which operations each kind of run may use through its tools: the
933 /// allowed and denied matrix.
934 #[test]
935 fn tools_matrix() {
936 let cases: [(&str, [bool; 6]); 12] = [
937 // implement revise answer review plan checks
938 ("get_issue", [true, true, true, true, true, false]),
939 ("create_issue", [true, true, true, false, true, false]),
940 ("add_comment", [true, true, true, true, false, false]),
941 (
942 "review_pull_request",
943 [false, false, false, true, false, false],
944 ),
945 ("remember", [true, true, true, false, false, false]),
946 ("take_messages", [true, true, true, false, false, false]),
947 ("record_session", [false, false, false, false, false, false]),
948 (
949 "merge_pull_request",
950 [false, false, false, false, false, false],
951 ),
952 (
953 "update_repo_settings",
954 [false, false, false, false, false, false],
955 ),
956 ("create_webhook", [false, false, false, false, false, false]),
957 (
958 "set_actions_secret",
959 [false, false, false, false, false, false],
960 ),
961 ("assign_issue", [false, false, false, false, false, false]),
962 ];
963 let kinds = [
964 K::Implement,
965 K::Revise,
966 K::Answer,
967 K::Review,
968 K::Plan,
969 K::Checks,
970 ];
971 for (operation, expected) in cases {
972 for (kind, allowed) in kinds.into_iter().zip(expected) {
973 assert_eq!(
974 op(kind, Tools, operation).allowed,
975 allowed,
976 "{operation} by a {} run's tools",
977 kind.as_str()
978 );
979 }
980 }
981 }
982
983 #[test]
984 fn runner_matrix() {
985 assert!(op(K::Implement, Runner, "record_session").allowed);
986 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
987 assert!(op(K::Revise, Runner, "record_session").allowed);
988 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
989 assert!(!op(K::Implement, Runner, "create_issue").allowed);
990 assert!(!op(K::Review, Runner, "record_session").allowed);
991 assert!(!op(K::Checks, Runner, "get_issue").allowed);
992 }
993
994 #[test]
995 fn settings_billing_tokens_and_members_are_never_reachable() {
996 for kind in RunCredentialKind::ALL {
997 for usage in [Runner, Tools] {
998 for operation in NEVER.iter().copied() {
999 let decision = op(kind, usage, operation);
1000 assert!(!decision.allowed);
1001 assert_eq!(decision.rule, "never");
1002 }
1003 }
1004 }
1005 // Even a scope that lists one is refused.
1006 let mut wide = scope(K::Implement, Tools);
1007 wide.operations.push("merge_pull_request".to_owned());
1008 let user = agent(&["acme"], wide.clone());
1009 let decision = decide_operation(
1010 &user,
1011 &wide,
1012 "merge_pull_request",
1013 Some(&path("acme", "rocket")),
1014 true,
1015 Some(7),
1016 );
1017 assert_eq!(decision.rule, "never");
1018 }
1019
1020 #[test]
1021 fn another_repository_is_refused() {
1022 let scope = scope(K::Implement, Tools);
1023 let user = agent(&["acme"], scope.clone());
1024 let decision = decide_operation(
1025 &user,
1026 &scope,
1027 "create_issue",
1028 Some(&path("acme", "other")),
1029 true,
1030 None,
1031 );
1032 assert!(!decision.allowed);
1033 assert_eq!(decision.rule, "scope:repository");
1034 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1035 assert_eq!(decision.rule, "scope:repository");
1036 // The repository's name is matched without regard to case.
1037 let decision = decide_operation(
1038 &user,
1039 &scope,
1040 "create_issue",
1041 Some(&path("Acme", "Rocket")),
1042 true,
1043 None,
1044 );
1045 assert!(decision.allowed);
1046 assert_eq!(decision.rule, "run:implement/tools");
1047 }
1048
1049 #[test]
1050 fn the_permission_is_the_intersection_with_the_person() {
1051 let scope = scope(K::Implement, Tools);
1052 // The person left the workspace: their agent can do nothing there.
1053 let user = agent(&[], scope.clone());
1054 let decision = decide_operation(
1055 &user,
1056 &scope,
1057 "get_issue",
1058 Some(&path("acme", "rocket")),
1059 true,
1060 Some(1),
1061 );
1062 assert!(!decision.allowed);
1063 assert_eq!(decision.rule, "on-behalf-of:membership");
1064 // And an owner's agent is only ever a member.
1065 let owner = vec![
1066 Membership {
1067 slug: "acme".to_owned(),
1068 role: Role::Owner,
1069 name: None,
1070 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1071 base_permission: Some(BasePermission::None),
Merge branch 'worktree-agent-ad7c6d88d93adc817'1072 team_creation: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1073 },
1074 Membership::member("elsewhere"),
1075 ];
1076 let memberships = intersect(&owner, "Acme");
1077 assert_eq!(memberships.len(), 1);
1078 assert_eq!(memberships[0].slug, "acme");
1079 assert_eq!(memberships[0].role, Role::Member);
1080 assert!(intersect(&owner, "nowhere").is_empty());
1081 }
1082
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1083 /// An agent gets at most the person's role on the repository, and
1084 /// never more than Write; nothing outside the run's workspace.
1085 #[test]
1086 fn an_agent_has_at_most_its_persons_role() {
1087 use crate::access::{Capability, RepoRef, can, permission};
1088 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1089 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1090 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1091 let tools = scope(K::Implement, Tools);
1092 let scope = scope(K::Implement, Runner);
1093 // An owner's agent: Write, never Admin.
1094 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1095 let mut agent_user = agent(&[], scope.clone());
1096 agent_user.workspaces = intersect(&owner, "acme");
1097 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1098 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1099 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1100 // A member whose workspace gives Read: Read, so it cannot push.
1101 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1102 agent_user.workspaces = intersect(&reader, "acme");
1103 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1104 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1105 // An outside collaborator with Maintain on one repository: Write
1106 // there, nothing elsewhere, and the run is allowed.
1107 let grants = [
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1108 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1109 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin, team: None },
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1110 ];
1111 agent_user.workspaces = intersect(&[], "acme");
1112 agent_user.grants = intersect_grants(&grants, "Acme");
1113 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1114 assert_eq!(permission(Some(&agent_user), other), None);
1115 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1116 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1117 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1118 // The person, downstream of a runner's credential, carries the same.
1119 let person = as_person(&agent_user).expect("a runner acts as the person");
1120 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1121 }
1122
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1123 #[test]
1124 fn a_runner_changes_only_its_own_pull_request() {
1125 let scope = scope(K::Implement, Runner);
1126 let user = agent(&["acme"], scope.clone());
1127 let repo = path("acme", "rocket");
1128 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1129 assert!(!other.allowed);
1130 assert_eq!(other.rule, "scope:pull");
1131 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1132 assert!(own.allowed);
1133 // Reading another is fine.
1134 assert!(
1135 decide_operation(
1136 &user,
1137 &scope,
1138 "get_pull_request",
1139 Some(&repo),
1140 true,
1141 Some(8)
1142 )
1143 .allowed
1144 );
1145 }
1146
1147 #[test]
1148 fn git_matrix() {
1149 let fork = path("pulls", "pul_7");
1150 let upstream = path("acme", "rocket");
1151 let elsewhere = path("acme", "billing");
1152 let implement = scope(K::Implement, Runner);
1153 assert!(decide_git(&implement, &fork, true).allowed);
1154 assert!(decide_git(&implement, &fork, false).allowed);
1155 assert!(decide_git(&implement, &upstream, false).allowed);
1156 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1157 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1158 let review = scope(K::Review, Runner);
1159 assert!(decide_git(&review, &upstream, false).allowed);
1160 assert!(!decide_git(&review, &upstream, true).allowed);
1161 assert!(!decide_git(&review, &fork, true).allowed);
1162 // A tools token made before run credentials never reaches git.
1163 let old = AgentScope {
1164 repo: upstream.clone(),
1165 operations: vec!["get_issue".to_owned()],
1166 run: None,
1167 };
1168 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1169 // Nor does an agent's tools token.
1170 assert_eq!(
1171 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1172 "git:not-a-run"
1173 );
1174 }
1175
1176 #[test]
1177 fn a_push_moves_only_granted_branches() {
1178 let update = scope(K::Update, Runner);
1179 let repo = path("acme", "rocket");
1180 let refs = |names: &[&str]| {
1181 names
1182 .iter()
1183 .map(|name| (*name).to_owned())
1184 .collect::<Vec<_>>()
1185 };
1186 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1187 assert_eq!(
1188 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1189 "git:ref"
1190 );
1191 assert_eq!(
1192 decide_refs(
1193 &update,
1194 &repo,
1195 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1196 )
1197 .rule,
1198 "git:ref"
1199 );
1200 let implement = scope(K::Implement, Runner);
1201 assert!(
1202 decide_refs(
1203 &implement,
1204 &path("pulls", "pul_7"),
1205 &refs(&["refs/heads/main"])
1206 )
1207 .allowed
1208 );
1209 }
1210
1211 #[test]
1212 fn a_runner_acts_downstream_as_the_person() {
1213 let user = agent(&["acme"], scope(K::Implement, Runner));
1214 let person = as_person(&user).unwrap();
1215 assert_eq!(person.id, "usr_1");
1216 assert_eq!(person.username, "syntaqx");
1217 assert_eq!(person.kind, PrincipalKind::User);
1218 assert!(person.is_member("acme"));
1219 assert!(person.acting.is_none());
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent1220 assert_eq!(describe(&user), "g1t on behalf of syntaqx");
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1221 // The tools act as the agent.
1222 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1223 }
1224
1225 #[test]
1226 fn scopes_without_a_run_still_parse() {
1227 let old: AgentScope = serde_json::from_str(
1228 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1229 )
1230 .unwrap();
1231 assert!(old.run.is_none());
1232 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1233 assert!(written.contains(r#""use":"tools""#));
1234 assert!(written.contains(r#""kind":"review""#));
1235 let back: AgentScope = serde_json::from_str(&written).unwrap();
1236 assert_eq!(back.run.unwrap().kind, K::Review);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1237 // Only g1t's own runs say so; every other reads as not.
1238 assert!(!written.contains("system"));
1239 assert!(!back_run(&written).system);
1240 let mut own = scope(K::Bump, Runner);
1241 own.run.as_mut().unwrap().system = true;
1242 let written = serde_json::to_string(&own).unwrap();
1243 assert!(written.contains(r#""system":true"#));
1244 assert!(back_run(&written).system);
1245 }
1246
1247 fn back_run(written: &str) -> RunBinding {
1248 serde_json::from_str::<AgentScope>(written).unwrap().run.unwrap()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1249 }
1250}

This file's history is long; its oldest lines are credited to the oldest commit read.