Skip to content
1,267 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",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look237 "list_deleted_repos",
238 "list_collaborators",
239 "get_collaborator_permission",
240 "list_repo_invitations",
241 "list_my_repo_invitations",
242 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar243 "list_teams",
244 "get_team",
245 "list_team_members",
246 "list_child_teams",
247 "list_team_repos",
248 "list_user_teams",
249 "get_codeowners_errors",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API250 "get_repo_settings",
Fast pages, required checks on the branch, self-hosted runners, honest incidents251 "list_check_names",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API252 "get_merge_queue",
253 "recall",
254 "list_issues",
255 "get_issue",
256 "get_plan",
257 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar258 "list_issue_labels",
259 "list_milestones",
260 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API261 "list_pull_requests",
262 "get_pull_request",
263 "read_session",
264 "get_pull_request_changes",
265 "list_events",
266 "get_context",
267 "search_context",
268 "get_entity",
Search across all of g1t, Explore, and a command palette269 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API270 "list_workflows",
271 "list_workflow_runs",
272 "get_workflow_run",
273 "get_job_logs",
Checks: statuses and check runs on every commit, for CI and integrations274 "list_commit_statuses",
275 "get_combined_status",
276 "list_check_runs_for_ref",
277 "get_check_run",
278 "list_check_run_annotations",
279 "list_check_suites_for_ref",
280 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API281 "list_integrations",
282 "get_model_routes",
283 "list_webhooks",
284 "list_webhook_deliveries",
285 "list_actions_secrets",
286 "list_actions_variables",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily287 "list_security_alerts",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar288 "list_secret_scanning_alerts",
289 "get_secret_scanning_alert",
290 "list_secret_scanning_locations",
291 "list_bypass_requests",
292 "list_custom_patterns",
293 "list_code_scanning_alerts",
294 "get_code_scanning_alert",
295 "list_code_scanning_analyses",
296 "get_sarif_upload",
297 "list_vulnerability_alerts",
298 "get_vulnerability_alert",
299 "get_dependency_graph",
300 "get_sbom",
301 "compare_dependencies",
302 "get_security_settings",
303 "get_workspace_security_settings",
304 "get_security_overview",
API: notifications over REST and MCP, with notifications scopes305 "list_notifications",
306 "get_notification_thread",
307 "get_thread_subscription",
308 "get_repo_subscription",
309 "list_watched_repos",
API: pinned projects over REST and MCP310 "list_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API311];
312
313/// What no agent's token may ever do, whatever its scope says: workspaces,
314/// repositories' settings, members, tokens, billing, integrations,
315/// webhooks, secrets, workflows' controls, merging, and putting more agents
316/// to work.
317pub const NEVER: &[&str] = &[
Usage, Billing settings and prepaid AI credit; fixes from the UX audit318 // Billing is people's: agents never spend or change it.
319 "set_budget",
320 "buy_ai_credit",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API321 "create_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look322 "delete_workspace",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily323 "update_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look324 "transfer_repo",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API325 "create_repo",
326 "update_repo",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look327 "delete_repo",
328 "list_deleted_repos",
329 "restore_repo",
330 "purge_repo",
331 "rename_repo",
332 "archive_repo",
333 "unarchive_repo",
334 "set_repo_visibility",
335 "rename_branch",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API336 "update_repo_settings",
337 "merge_pull_request",
338 "assign_issue",
339 "plan_work",
340 "apply_plan",
341 "import_issue",
342 "list_integrations",
343 "connect_integration",
344 "disconnect_integration",
345 "test_integration",
346 "get_model_routes",
347 "set_model_routes",
348 "list_webhooks",
349 "create_webhook",
350 "update_webhook",
351 "delete_webhook",
352 "ping_webhook",
353 "list_webhook_deliveries",
354 "redeliver_webhook",
355 "dispatch_workflow",
356 "cancel_workflow_run",
357 "rerun_workflow_run",
358 "update_workflow",
Checks: statuses and check runs on every commit, for CI and integrations359 // An agent never reports checks on its own work, nor asks for them
360 // to run again: what checks say is the integrations' to say.
361 "create_commit_status",
362 "create_check_run",
363 "update_check_run",
364 "rerequest_check_run",
365 "rerequest_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API366 "list_actions_secrets",
367 "set_actions_secret",
368 "delete_actions_secret",
369 "list_actions_variables",
370 "set_actions_variable",
371 "delete_actions_variable",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look372 "list_collaborators",
373 "get_collaborator_permission",
374 "add_collaborator",
375 "update_collaborator",
376 "remove_collaborator",
377 "list_repo_invitations",
378 "revoke_repo_invitation",
379 "list_my_repo_invitations",
380 "accept_repo_invitation",
381 "decline_repo_invitation",
382 "set_base_permission",
383 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar384 // Teams: who is in which, and what they reach, is for people.
385 "create_team",
386 "update_team",
387 "delete_team",
388 "set_team_member",
389 "remove_team_member",
390 "set_team_repo",
391 "remove_team_repo",
392 "set_team_review_assignment",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily393 // Dismissing a secret lets it through push protection.
394 "dismiss_security_alert",
395 "reopen_security_alert",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar396 // Nor any other decision about security: closing or reopening an
397 // alert, pushing past push protection or deciding who may, changing
398 // what is looked for or when checks fail, or putting more agents to
399 // work. An agent fixes what it finds in its own pull request.
400 "update_secret_scanning_alert",
401 "bypass_push_protection",
402 "review_bypass_request",
403 "create_custom_pattern",
404 "update_custom_pattern",
405 "delete_custom_pattern",
406 "update_code_scanning_alert",
407 "update_vulnerability_alert",
408 "fix_security_alert",
409 "update_security_settings",
410 "update_workspace_security_settings",
API: notifications over REST and MCP, with notifications scopes411 // A person's own inbox: g1t's agents act as g1t, which has none.
412 "list_notifications",
413 "get_notification_thread",
414 "mark_notifications_read",
415 "mark_thread_read",
416 "mark_thread_done",
417 "save_thread",
418 "snooze_thread",
419 "get_thread_subscription",
420 "set_thread_subscription",
421 "delete_thread_subscription",
422 "get_repo_subscription",
423 "set_repo_subscription",
424 "delete_repo_subscription",
425 "list_watched_repos",
API: pinned projects over REST and MCP426 // Pins are a person's own, as the inbox is.
427 "list_pinned_projects",
428 "pin_project",
429 "unpin_project",
430 "reorder_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API431];
432
433/// Reading what an agent needs to know about its repository.
434const TOOLS_READ: &[&str] = &[
435 "get_repo",
436 "list_issues",
437 "get_issue",
438 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar439 "list_issue_labels",
440 "list_milestones",
441 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API442 "list_pull_requests",
443 "get_pull_request",
444 "get_pull_request_changes",
445 "read_session",
446 "get_merge_queue",
447 "list_events",
448 "recall",
449 "search_context",
450 "get_entity",
Search across all of g1t, Explore, and a command palette451 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API452 "list_workflows",
453 "list_workflow_runs",
454 "get_workflow_run",
455 "get_job_logs",
Checks: statuses and check runs on every commit, for CI and integrations456 "list_commit_statuses",
457 "get_combined_status",
458 "list_check_runs_for_ref",
459 "get_check_run",
460 "list_check_run_annotations",
461 "list_check_suites_for_ref",
462 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API463];
464
465pub fn is_read(operation: &str) -> bool {
466 READ_OPERATIONS.contains(&operation)
467}
468
469/// The API and MCP operations a run of `kind` may use with a credential
470/// for `usage`. Git is separate: see [`decide_git`].
471pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
472 use RunCredentialKind as K;
473 let mut operations: Vec<&'static str> = Vec::new();
474 match usage {
475 CredentialUse::Runner => {
476 if kind.works_on_a_pull() {
477 operations.extend(["get_repo", "get_pull_request", "record_session"]);
478 }
479 if kind == K::Implement {
480 operations.push("mark_pull_request_ready");
481 }
482 }
483 CredentialUse::Tools => match kind {
484 K::Implement | K::Revise | K::Answer => {
485 operations.extend(TOOLS_READ.iter().copied());
486 operations.extend([
487 "create_issue",
488 "add_comment",
489 "take_messages",
490 "remember",
491 "message_agent",
492 "answer_message",
493 "get_context",
494 ]);
495 }
496 K::Review => {
497 operations.extend(TOOLS_READ.iter().copied());
498 operations.extend(["add_comment", "review_pull_request", "get_context"]);
499 }
500 K::Plan => {
501 operations.extend(TOOLS_READ.iter().copied());
502 operations.extend(["create_issue", "get_context"]);
503 }
504 K::Update => operations.extend(TOOLS_READ.iter().copied()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily505 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 API506 },
507 }
508 operations
509}
510
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step511/// What a run's credential may do, in the scope vocabulary that access
512/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
513/// for a runner, git's. Its operations, its repository and its run still
514/// bound it more tightly than these scopes say.
515pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
516 use crate::scopes::{Scope, normalize, scope_for};
517 let mut scopes: Vec<Scope> = operations_for(kind, usage)
518 .into_iter()
519 .filter_map(scope_for)
520 .collect();
521 if usage == CredentialUse::Runner {
522 scopes.push(Scope::CodeRead);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily523 if matches!(
524 kind,
525 RunCredentialKind::Implement
526 | RunCredentialKind::Revise
527 | RunCredentialKind::Answer
528 | RunCredentialKind::Update
529 | RunCredentialKind::Bump
530 ) {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step531 scopes.push(Scope::CodeWrite);
532 }
533 }
534 normalize(&mut scopes);
535 scopes
536}
537
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API538/// Operations that change a pull request, which a runner may do only to
539/// the pull request its run works on.
540const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
541
542/// Whether something was allowed, and the rule that decided it.
543#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
544pub struct Decision {
545 pub allowed: bool,
546 /// A short, stable name: `run:implement/tools`, `never`,
547 /// `scope:repository` and so on. Shown in the audit log.
548 pub rule: String,
549 /// Why it was refused, for the caller.
550 #[serde(default, skip_serializing_if = "Option::is_none")]
551 pub reason: Option<String>,
552}
553
554impl Decision {
555 pub fn allow(rule: impl Into<String>) -> Self {
556 Decision {
557 allowed: true,
558 rule: rule.into(),
559 reason: None,
560 }
561 }
562
563 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
564 Decision {
565 allowed: false,
566 rule: rule.into(),
567 reason: Some(reason.into()),
568 }
569 }
570}
571
572fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
573 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
574}
575
576fn scope_rule(scope: &AgentScope) -> String {
577 match &scope.run {
578 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
579 None => "agent-token".to_owned(),
580 }
581}
582
583/// Whether `user`, resolved from an agent's token with `scope`, may use
584/// `operation`. `repo` is the repository the call names, if any, and
585/// `needs_repo` whether the operation is about one; `number` the issue or
586/// pull request it names.
587pub fn decide_operation(
588 user: &User,
589 scope: &AgentScope,
590 operation: &str,
591 repo: Option<&RepoPath>,
592 needs_repo: bool,
593 number: Option<u32>,
594) -> Decision {
595 let who = "A g1t agent's token";
596 if NEVER.contains(&operation) {
597 return Decision::deny(
598 "never",
599 format!(
600 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
601 ),
602 );
603 }
604 if !scope.operations.iter().any(|name| name == operation) {
605 return Decision::deny(
606 "scope:operation",
607 format!("{who} for this run cannot use {operation}."),
608 );
609 }
610 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
611 return Decision::deny(
612 "scope:repository",
613 format!(
614 "{who} works in {}/{} only.",
615 scope.repo.namespace, scope.repo.name
616 ),
617 );
618 }
619 // 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 look620 // in the repository's workspace, as a member or with a role on its
621 // repositories. What it may do in the repository itself is their
622 // role there, which services check (`access::can`).
623 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 API624 return Decision::deny(
625 "on-behalf-of:membership",
626 format!(
627 "The person this agent works for is no longer a member of {}.",
628 scope.repo.namespace
629 ),
630 );
631 }
632 if let Some(run) = &scope.run
633 && run.usage == CredentialUse::Runner
634 && PULL_WRITES.contains(&operation)
635 && run.number.is_some()
636 && number != run.number
637 {
638 return Decision::deny(
639 "scope:pull",
640 format!(
641 "{who} can change pull request #{} only.",
642 run.number.unwrap_or_default()
643 ),
644 );
645 }
646 Decision::allow(scope_rule(scope))
647}
648
649/// Whether a run credential may clone or fetch (`write` false), or push to
650/// (`write` true), the repository at `repo`.
651pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
652 let Some(run) = scope
653 .run
654 .as_ref()
655 .filter(|run| run.usage == CredentialUse::Runner)
656 else {
657 return Decision::deny(
658 "git:not-a-run",
659 "A g1t agent's tools token cannot be used with git.",
660 );
661 };
662 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
663 if write {
664 return if pushable {
665 Decision::allow(format!("{}:push", scope_rule(scope)))
666 } else {
667 Decision::deny(
668 "git:push",
669 format!(
670 "A {} run cannot push to {}/{}.",
671 run.kind.as_str(),
672 repo.namespace,
673 repo.name
674 ),
675 )
676 };
677 }
678 let readable = pushable
679 || same_repo(&scope.repo, repo)
680 || run.read.iter().any(|path| same_repo(path, repo));
681 if readable {
682 Decision::allow(format!("{}:read", scope_rule(scope)))
683 } else {
684 Decision::deny(
685 "git:read",
686 format!(
687 "A {} run cannot read {}/{}.",
688 run.kind.as_str(),
689 repo.namespace,
690 repo.name
691 ),
692 )
693 }
694}
695
696/// Whether a push to `repo` is limited to certain branches, so that the
697/// refs it moves have to be read and checked with [`decide_refs`].
698pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
699 scope
700 .run
701 .iter()
702 .flat_map(|run| run.push.iter())
703 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
704}
705
706/// Whether a push to `repo` may move `refs` (full refs, such as
707/// `refs/heads/main`). Tags are never a run's to move.
708pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
709 let repo_decision = decide_git(scope, repo, true);
710 if !repo_decision.allowed {
711 return repo_decision;
712 }
713 let grants: Vec<&GitGrant> = scope
714 .run
715 .iter()
716 .flat_map(|run| run.push.iter())
717 .filter(|grant| same_repo(&grant.repo, repo))
718 .collect();
719 for git_ref in refs {
720 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
721 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
722 };
723 let allowed = grants
724 .iter()
725 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
726 if !allowed {
727 return Decision::deny(
728 "git:ref",
729 format!(
730 "A run cannot push to {branch} in {}/{}.",
731 repo.namespace, repo.name
732 ),
733 );
734 }
735 }
736 repo_decision
737}
738
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look739/// The most an agent may be on a repository, whoever it works for: it
740/// can push, merge and run, never change settings or who has access.
741pub const AGENT_CEILING: RepoRole = RepoRole::Write;
742
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API743/// 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 look744/// workspace, as a member, only if the person is in it now, with the
745/// person's role on its repositories (an owner's Admin included) cut down
746/// to [`AGENT_CEILING`].
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API747pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
748 let namespace = namespace.to_lowercase();
749 person
750 .iter()
751 .filter(|membership| membership.slug == namespace)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look752 .map(|membership| {
753 let base = match membership.role {
754 Role::Owner => BasePermission::Admin,
755 Role::Member => membership.base_permission.unwrap_or_default(),
756 };
757 Membership {
758 role: Role::Member,
759 base_permission: Some(match base {
760 BasePermission::Admin => BasePermission::Write,
761 base => base,
762 }),
763 ..membership.clone()
764 }
765 })
766 .collect()
767}
768
769/// The repository grants an agent working for `person` has: those in the
770/// run's workspace, each cut down to [`AGENT_CEILING`].
771pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
772 let namespace = namespace.to_lowercase();
773 person
774 .iter()
775 .filter(|grant| grant.workspace == namespace)
776 .map(|grant| RepoGrant {
777 role: grant.role.min(AGENT_CEILING),
778 ..grant.clone()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API779 })
780 .collect()
781}
782
783/// Who a runner's credential acts as downstream: the person, with only the
784/// agent's (already intersected) memberships. `None` for anything else.
785pub fn as_person(user: &User) -> Option<User> {
786 let acting = user.acting.as_ref()?;
787 if user.kind != PrincipalKind::Agent {
788 return None;
789 }
790 let run = acting.run()?;
791 if run.usage != CredentialUse::Runner {
792 return None;
793 }
794 Some(User {
795 id: acting.on_behalf_of.id.clone(),
796 username: acting.on_behalf_of.username.clone(),
797 kind: PrincipalKind::User,
798 verified: user.verified,
799 workspaces: user.workspaces.clone(),
800 avatar: None,
801 acting: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look802 grants: user.grants.clone(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step803 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API804 })
805}
806
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent807/// 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 API808pub fn describe(user: &User) -> String {
809 match &user.acting {
810 Some(acting) => format!(
811 "{} on behalf of {}",
812 acting.agent, acting.on_behalf_of.username
813 ),
814 None => user.username.clone(),
815 }
816}
817
818#[cfg(test)]
819mod tests {
820 use super::*;
821
822 #[test]
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step823 fn a_run_s_scopes_are_never_admin() {
824 for kind in RunCredentialKind::ALL {
825 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
826 let scopes = run_scopes(kind, usage);
827 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
828 }
829 }
830 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
831 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
832 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
833 }
834
835 #[test]
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API836 fn agents_can_search_the_context_hub() {
837 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
838 let tools = operations_for(kind, CredentialUse::Tools);
839 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
840 }
841 assert!(is_read("search_context") && is_read("get_entity"));
842 }
843
Search across all of g1t, Explore, and a command palette844 #[test]
845 fn agents_can_search_all_of_g1t() {
846 // Site-wide search only reads: every run that reads its repository
847 // may use it, and nothing that never reads gets it.
848 assert!(is_read("search"));
849 assert!(!NEVER.contains(&"search"));
850 for kind in [
851 RunCredentialKind::Implement,
852 RunCredentialKind::Revise,
853 RunCredentialKind::Answer,
854 RunCredentialKind::Review,
855 RunCredentialKind::Plan,
856 RunCredentialKind::Update,
857 ] {
858 let tools = operations_for(kind, CredentialUse::Tools);
859 assert!(tools.contains(&"search"), "{kind:?} should search");
860 // The context hub's search stays its own tool beside it.
861 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
862 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily863 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
Search across all of g1t, Explore, and a command palette864 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
865 }
866 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
867 }
868
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API869 fn path(namespace: &str, name: &str) -> RepoPath {
870 RepoPath {
871 namespace: namespace.to_owned(),
872 name: name.to_owned(),
873 }
874 }
875
876 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
877 AgentScope {
878 repo: path("acme", "rocket"),
879 operations: operations_for(kind, usage)
880 .into_iter()
881 .map(str::to_owned)
882 .collect(),
883 run: Some(RunBinding {
884 kind,
885 usage,
886 run_id: Some("run_1".to_owned()),
887 number: Some(7),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent888 agent: "g1t".to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily889 system: false,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API890 read: vec![path("acme", "rocket")],
891 push: match kind {
892 RunCredentialKind::Implement
893 | RunCredentialKind::Revise
894 | RunCredentialKind::Answer => vec![GitGrant {
895 repo: path("pulls", "pul_7"),
896 branch: None,
897 }],
898 RunCredentialKind::Update => vec![GitGrant {
899 repo: path("acme", "rocket"),
900 branch: Some("fix-login".to_owned()),
901 }],
902 _ => vec![],
903 },
904 }),
905 }
906 }
907
908 fn agent(member_of: &[&str], scope: AgentScope) -> User {
909 User {
910 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-agent911 username: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API912 kind: PrincipalKind::Agent,
913 verified: true,
914 workspaces: member_of
915 .iter()
916 .map(|slug| Membership::member(*slug))
917 .collect(),
918 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look919 grants: Vec::new(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step920 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API921 acting: Some(Box::new(Acting {
922 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-agent923 agent: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API924 on_behalf_of: Principal {
925 id: "usr_1".to_owned(),
926 username: "syntaqx".to_owned(),
927 },
928 scope,
929 })),
930 }
931 }
932
933 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
934 let scope = scope(kind, usage);
935 let user = agent(&["acme"], scope.clone());
936 decide_operation(
937 &user,
938 &scope,
939 operation,
940 Some(&path("acme", "rocket")),
941 true,
942 Some(7),
943 )
944 }
945
946 use CredentialUse::{Runner, Tools};
947 use RunCredentialKind as K;
948
949 /// Which operations each kind of run may use through its tools: the
950 /// allowed and denied matrix.
951 #[test]
952 fn tools_matrix() {
953 let cases: [(&str, [bool; 6]); 12] = [
954 // implement revise answer review plan checks
955 ("get_issue", [true, true, true, true, true, false]),
956 ("create_issue", [true, true, true, false, true, false]),
957 ("add_comment", [true, true, true, true, false, false]),
958 (
959 "review_pull_request",
960 [false, false, false, true, false, false],
961 ),
962 ("remember", [true, true, true, false, false, false]),
963 ("take_messages", [true, true, true, false, false, false]),
964 ("record_session", [false, false, false, false, false, false]),
965 (
966 "merge_pull_request",
967 [false, false, false, false, false, false],
968 ),
969 (
970 "update_repo_settings",
971 [false, false, false, false, false, false],
972 ),
973 ("create_webhook", [false, false, false, false, false, false]),
974 (
975 "set_actions_secret",
976 [false, false, false, false, false, false],
977 ),
978 ("assign_issue", [false, false, false, false, false, false]),
979 ];
980 let kinds = [
981 K::Implement,
982 K::Revise,
983 K::Answer,
984 K::Review,
985 K::Plan,
986 K::Checks,
987 ];
988 for (operation, expected) in cases {
989 for (kind, allowed) in kinds.into_iter().zip(expected) {
990 assert_eq!(
991 op(kind, Tools, operation).allowed,
992 allowed,
993 "{operation} by a {} run's tools",
994 kind.as_str()
995 );
996 }
997 }
998 }
999
1000 #[test]
1001 fn runner_matrix() {
1002 assert!(op(K::Implement, Runner, "record_session").allowed);
1003 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
1004 assert!(op(K::Revise, Runner, "record_session").allowed);
1005 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
1006 assert!(!op(K::Implement, Runner, "create_issue").allowed);
1007 assert!(!op(K::Review, Runner, "record_session").allowed);
1008 assert!(!op(K::Checks, Runner, "get_issue").allowed);
1009 }
1010
1011 #[test]
1012 fn settings_billing_tokens_and_members_are_never_reachable() {
1013 for kind in RunCredentialKind::ALL {
1014 for usage in [Runner, Tools] {
1015 for operation in NEVER.iter().copied() {
1016 let decision = op(kind, usage, operation);
1017 assert!(!decision.allowed);
1018 assert_eq!(decision.rule, "never");
1019 }
1020 }
1021 }
1022 // Even a scope that lists one is refused.
1023 let mut wide = scope(K::Implement, Tools);
1024 wide.operations.push("merge_pull_request".to_owned());
1025 let user = agent(&["acme"], wide.clone());
1026 let decision = decide_operation(
1027 &user,
1028 &wide,
1029 "merge_pull_request",
1030 Some(&path("acme", "rocket")),
1031 true,
1032 Some(7),
1033 );
1034 assert_eq!(decision.rule, "never");
1035 }
1036
1037 #[test]
1038 fn another_repository_is_refused() {
1039 let scope = scope(K::Implement, Tools);
1040 let user = agent(&["acme"], scope.clone());
1041 let decision = decide_operation(
1042 &user,
1043 &scope,
1044 "create_issue",
1045 Some(&path("acme", "other")),
1046 true,
1047 None,
1048 );
1049 assert!(!decision.allowed);
1050 assert_eq!(decision.rule, "scope:repository");
1051 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1052 assert_eq!(decision.rule, "scope:repository");
1053 // The repository's name is matched without regard to case.
1054 let decision = decide_operation(
1055 &user,
1056 &scope,
1057 "create_issue",
1058 Some(&path("Acme", "Rocket")),
1059 true,
1060 None,
1061 );
1062 assert!(decision.allowed);
1063 assert_eq!(decision.rule, "run:implement/tools");
1064 }
1065
1066 #[test]
1067 fn the_permission_is_the_intersection_with_the_person() {
1068 let scope = scope(K::Implement, Tools);
1069 // The person left the workspace: their agent can do nothing there.
1070 let user = agent(&[], scope.clone());
1071 let decision = decide_operation(
1072 &user,
1073 &scope,
1074 "get_issue",
1075 Some(&path("acme", "rocket")),
1076 true,
1077 Some(1),
1078 );
1079 assert!(!decision.allowed);
1080 assert_eq!(decision.rule, "on-behalf-of:membership");
1081 // And an owner's agent is only ever a member.
1082 let owner = vec![
1083 Membership {
1084 slug: "acme".to_owned(),
1085 role: Role::Owner,
1086 name: None,
1087 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1088 base_permission: Some(BasePermission::None),
Merge branch 'worktree-agent-ad7c6d88d93adc817'1089 team_creation: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1090 },
1091 Membership::member("elsewhere"),
1092 ];
1093 let memberships = intersect(&owner, "Acme");
1094 assert_eq!(memberships.len(), 1);
1095 assert_eq!(memberships[0].slug, "acme");
1096 assert_eq!(memberships[0].role, Role::Member);
1097 assert!(intersect(&owner, "nowhere").is_empty());
1098 }
1099
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1100 /// An agent gets at most the person's role on the repository, and
1101 /// never more than Write; nothing outside the run's workspace.
1102 #[test]
1103 fn an_agent_has_at_most_its_persons_role() {
1104 use crate::access::{Capability, RepoRef, can, permission};
1105 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1106 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1107 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1108 let tools = scope(K::Implement, Tools);
1109 let scope = scope(K::Implement, Runner);
1110 // An owner's agent: Write, never Admin.
1111 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1112 let mut agent_user = agent(&[], scope.clone());
1113 agent_user.workspaces = intersect(&owner, "acme");
1114 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1115 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1116 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1117 // A member whose workspace gives Read: Read, so it cannot push.
1118 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1119 agent_user.workspaces = intersect(&reader, "acme");
1120 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1121 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1122 // An outside collaborator with Maintain on one repository: Write
1123 // there, nothing elsewhere, and the run is allowed.
1124 let grants = [
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1125 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1126 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 look1127 ];
1128 agent_user.workspaces = intersect(&[], "acme");
1129 agent_user.grants = intersect_grants(&grants, "Acme");
1130 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1131 assert_eq!(permission(Some(&agent_user), other), None);
1132 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1133 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1134 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1135 // The person, downstream of a runner's credential, carries the same.
1136 let person = as_person(&agent_user).expect("a runner acts as the person");
1137 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1138 }
1139
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1140 #[test]
1141 fn a_runner_changes_only_its_own_pull_request() {
1142 let scope = scope(K::Implement, Runner);
1143 let user = agent(&["acme"], scope.clone());
1144 let repo = path("acme", "rocket");
1145 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1146 assert!(!other.allowed);
1147 assert_eq!(other.rule, "scope:pull");
1148 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1149 assert!(own.allowed);
1150 // Reading another is fine.
1151 assert!(
1152 decide_operation(
1153 &user,
1154 &scope,
1155 "get_pull_request",
1156 Some(&repo),
1157 true,
1158 Some(8)
1159 )
1160 .allowed
1161 );
1162 }
1163
1164 #[test]
1165 fn git_matrix() {
1166 let fork = path("pulls", "pul_7");
1167 let upstream = path("acme", "rocket");
1168 let elsewhere = path("acme", "billing");
1169 let implement = scope(K::Implement, Runner);
1170 assert!(decide_git(&implement, &fork, true).allowed);
1171 assert!(decide_git(&implement, &fork, false).allowed);
1172 assert!(decide_git(&implement, &upstream, false).allowed);
1173 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1174 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1175 let review = scope(K::Review, Runner);
1176 assert!(decide_git(&review, &upstream, false).allowed);
1177 assert!(!decide_git(&review, &upstream, true).allowed);
1178 assert!(!decide_git(&review, &fork, true).allowed);
1179 // A tools token made before run credentials never reaches git.
1180 let old = AgentScope {
1181 repo: upstream.clone(),
1182 operations: vec!["get_issue".to_owned()],
1183 run: None,
1184 };
1185 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1186 // Nor does an agent's tools token.
1187 assert_eq!(
1188 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1189 "git:not-a-run"
1190 );
1191 }
1192
1193 #[test]
1194 fn a_push_moves_only_granted_branches() {
1195 let update = scope(K::Update, Runner);
1196 let repo = path("acme", "rocket");
1197 let refs = |names: &[&str]| {
1198 names
1199 .iter()
1200 .map(|name| (*name).to_owned())
1201 .collect::<Vec<_>>()
1202 };
1203 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1204 assert_eq!(
1205 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1206 "git:ref"
1207 );
1208 assert_eq!(
1209 decide_refs(
1210 &update,
1211 &repo,
1212 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1213 )
1214 .rule,
1215 "git:ref"
1216 );
1217 let implement = scope(K::Implement, Runner);
1218 assert!(
1219 decide_refs(
1220 &implement,
1221 &path("pulls", "pul_7"),
1222 &refs(&["refs/heads/main"])
1223 )
1224 .allowed
1225 );
1226 }
1227
1228 #[test]
1229 fn a_runner_acts_downstream_as_the_person() {
1230 let user = agent(&["acme"], scope(K::Implement, Runner));
1231 let person = as_person(&user).unwrap();
1232 assert_eq!(person.id, "usr_1");
1233 assert_eq!(person.username, "syntaqx");
1234 assert_eq!(person.kind, PrincipalKind::User);
1235 assert!(person.is_member("acme"));
1236 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-agent1237 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 API1238 // The tools act as the agent.
1239 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1240 }
1241
1242 #[test]
1243 fn scopes_without_a_run_still_parse() {
1244 let old: AgentScope = serde_json::from_str(
1245 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1246 )
1247 .unwrap();
1248 assert!(old.run.is_none());
1249 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1250 assert!(written.contains(r#""use":"tools""#));
1251 assert!(written.contains(r#""kind":"review""#));
1252 let back: AgentScope = serde_json::from_str(&written).unwrap();
1253 assert_eq!(back.run.unwrap().kind, K::Review);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1254 // Only g1t's own runs say so; every other reads as not.
1255 assert!(!written.contains("system"));
1256 assert!(!back_run(&written).system);
1257 let mut own = scope(K::Bump, Runner);
1258 own.run.as_mut().unwrap().system = true;
1259 let written = serde_json::to_string(&own).unwrap();
1260 assert!(written.contains(r#""system":true"#));
1261 assert!(back_run(&written).system);
1262 }
1263
1264 fn back_run(written: &str) -> RunBinding {
1265 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 API1266 }
1267}

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